public void ReloadUI() { txtName.text = purchaseable.GetName(); txtDescription.text = purchaseable.GetDescription(); txtCost.text = BitUtil.StringFormat(purchaseable.GetCost(), BitUtil.TextFormat.Short, true, true); imgIcon.sprite = purchaseable.GetIcon(); PurchaseableListMenu.PurchaseState purchaseState = presenter.GetPurchaseState(menuId, purchaseable); switch (purchaseState) { case PurchaseableListMenu.PurchaseState.Purchased: isLocked = false; imgBackground.color = purchasedBackgroundColor; txtName.color = purchasedTextColor; txtDescription.color = purchasedTextColor; btnBuy.gameObject.SetActive(false); break; case PurchaseableListMenu.PurchaseState.CannotPurchase: isLocked = false; imgBackground.color = unlockedBackgroundColor; txtName.color = normalTextColor; txtDescription.color = normalTextColor; btnBuy.gameObject.SetActive(false); break; case PurchaseableListMenu.PurchaseState.CanPurchase: isLocked = false; imgBackground.color = unlockedBackgroundColor; txtName.color = normalTextColor; txtDescription.color = normalTextColor; btnBuy.gameObject.SetActive(true); break; case PurchaseableListMenu.PurchaseState.Locked: isLocked = true; imgBackground.color = lockedBackgroundColor; txtName.color = normalTextColor; txtDescription.color = normalTextColor; btnBuy.gameObject.SetActive(true); // Visible but not clickable (interaction disabled in update) break; } quantityIndicator.interactable = false; if (presenter.ShouldDisplayProgressBar(menuId)) { quantityIndicator.gameObject.SetActive(true); int purchasedCount = presenter.GetPurchasedCount(menuId, purchaseable); quantityIndicator.value = ((float)purchasedCount / purchaseable.GetQuantity()); if (purchasedCount == 0) { quantityIndicatorLabel.text = ""; } else { quantityIndicatorLabel.text = "x" + purchasedCount.ToString("0"); } } else { quantityIndicator.gameObject.SetActive(false); // TODO: Should adjust labels to fill space left by the quantity indicator, but doesn't work well // and ReloadUI causes them to keep moving. // float quantityIndicatorHeight = quantityIndicator.GetComponent<RectTransform>().rect.height; // RectTransform rectName = txtName.GetComponent<RectTransform>(); // rectName.sizeDelta = new Vector2(rectName.sizeDelta.x, rectName.sizeDelta.y + (quantityIndicatorHeight/2)); // // RectTransform rectDescription = txtDescription.GetComponent<RectTransform>(); // rectDescription.sizeDelta = new Vector2(rectDescription.sizeDelta.x, rectDescription.sizeDelta.y + (quantityIndicatorHeight/2)); } }
public TableNameRecord(byte[] data, byte[] header) : base(data, header, false) { Name = Encoding.GetEncoding("iso-8859-1").GetString(header, 1, header.Length - 1); TableNumber = BitUtil.ToInt32(data, 0, false); }
internal int SelectBucketIndex(int bufferSize) { Debug.Assert(bufferSize >= 0); return(Math.Max(0, (32 - BitUtil.NumberOfLeadingZeros(bufferSize - 1)) - _minBufferLengthPow2)); }
void SetStoredBitsText() { txtStoredBits.text = BitUtil.StringFormat(GameManager.Instance.GameState.StoredBits, BitUtil.TextFormat.Long); }
/// <summary> /// /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="bitmapDefinedAsString"> /// Accept bitmap defined as a list of byte defined like this "B11111111", "B10000001" /// </param> /// <param name="w"></param> /// <param name="h"></param> /// <param name="color"></param> public void DrawBitmap(int16_t x, int16_t y, List <string> bitmapDefinedAsString, int16_t w, int16_t h, uint16_t color) { DrawBitmap(0, 0, BitUtil.ParseBinary(bitmapDefinedAsString), 8, 8, 1); }
/// <summary> /// Compute the length of the cnc file and return it. /// </summary> /// <param name="totalLengthOfBuffers"> in bytes </param> /// <param name="alignment"> for file length to adhere to</param> /// <returns> cnc file length in bytes </returns> public static int ComputeCncFileLength(int totalLengthOfBuffers, int alignment) { return(BitUtil.Align(END_OF_METADATA_OFFSET + totalLengthOfBuffers, alignment)); }
/// <summary> /// Poll for new messages in a stream. If new messages are found beyond the last consumed position then they /// will be delivered to the <seealso cref="IControlledFragmentHandler"/> up to a limited number of fragments as specified or /// the maximum position specified. /// <para> /// Use a <seealso cref="IControlledFragmentHandler"/> to assemble messages which span multiple fragments. /// /// </para> /// </summary> /// <param name="fragmentHandler"> to which message fragments are delivered. </param> /// <param name="maxPosition"> to consume messages up to. </param> /// <param name="fragmentLimit"> for the number of fragments to be consumed during one polling operation. </param> /// <returns> the number of fragments that have been consumed. </returns> /// <seealso cref="ControlledFragmentAssembler"/> /// <seealso cref="ImageControlledFragmentAssembler"/> public virtual int BoundedControlledPoll(IControlledFragmentHandler fragmentHandler, long maxPosition, int fragmentLimit) { if (_isClosed) { return(0); } var fragmentsRead = 0; var initialPosition = _subscriberPosition.Get(); var initialOffset = (int)initialPosition & _termLengthMask; var resultingOffset = initialOffset; var termBuffer = ActiveTermBuffer(initialPosition); var endOffset = (int)Math.Min(termBuffer.Capacity, (maxPosition - initialPosition + initialOffset)); _header.Buffer = termBuffer; try { while (fragmentsRead < fragmentLimit && resultingOffset < endOffset) { int length = FrameDescriptor.FrameLengthVolatile(termBuffer, resultingOffset); if (length <= 0) { break; } int frameOffset = resultingOffset; int alignedLength = BitUtil.Align(length, FrameDescriptor.FRAME_ALIGNMENT); resultingOffset += alignedLength; if (FrameDescriptor.IsPaddingFrame(termBuffer, frameOffset)) { continue; } _header.Offset = frameOffset; var action = fragmentHandler.OnFragment(termBuffer, frameOffset + DataHeaderFlyweight.HEADER_LENGTH, length - DataHeaderFlyweight.HEADER_LENGTH, _header); if (action == ControlledFragmentHandlerAction.ABORT) { resultingOffset -= alignedLength; break; } ++fragmentsRead; if (action == ControlledFragmentHandlerAction.BREAK) { break; } else if (action == ControlledFragmentHandlerAction.COMMIT) { initialPosition += (resultingOffset - initialOffset); initialOffset = resultingOffset; _subscriberPosition.SetOrdered(initialPosition); } } } catch (Exception t) { _errorHandler(t); } finally { long resultingPosition = initialPosition + (resultingOffset - initialOffset); if (resultingPosition > initialPosition) { _subscriberPosition.SetOrdered(resultingPosition); } } return(fragmentsRead); }
public void ReadBattleScene(String name) { name = "EVT_BATTLE_" + name; this.header = new SB2_HEAD(); TextAsset textAsset = AssetManager.Load <TextAsset>("BattleMap/BattleScene/" + name + "/dbfile0000.raw16", false); Byte[] bytes = textAsset.bytes; using (BinaryReader binaryReader = new BinaryReader(new MemoryStream(bytes))) { this.header.Ver = binaryReader.ReadByte(); this.header.PatCount = binaryReader.ReadByte(); this.header.TypCount = binaryReader.ReadByte(); this.header.AtkCount = binaryReader.ReadByte(); this.header.Flags = binaryReader.ReadUInt16(); this.PatAddr = new SB2_PATTERN[(Int32)this.header.PatCount]; this.MonAddr = new SB2_MON_PARM[(Int32)this.header.TypCount]; this.atk = new AA_DATA[(Int32)this.header.AtkCount]; binaryReader.BaseStream.Seek(8L, SeekOrigin.Begin); for (Int32 i = 0; i < (Int32)this.header.PatCount; i++) { SB2_PATTERN sb2_PATTERN = this.PatAddr[i] = new SB2_PATTERN(); sb2_PATTERN.Rate = binaryReader.ReadByte(); sb2_PATTERN.MonCount = binaryReader.ReadByte(); sb2_PATTERN.Camera = binaryReader.ReadByte(); sb2_PATTERN.Pad0 = binaryReader.ReadByte(); sb2_PATTERN.AP = binaryReader.ReadUInt32(); for (Int32 j = 0; j < 4; j++) { SB2_PUT sb2_PUT = sb2_PATTERN.Put[j] = new SB2_PUT(); sb2_PUT.TypeNo = binaryReader.ReadByte(); sb2_PUT.Flags = binaryReader.ReadByte(); sb2_PUT.Pease = binaryReader.ReadByte(); sb2_PUT.Pad = binaryReader.ReadByte(); sb2_PUT.Xpos = binaryReader.ReadInt16(); sb2_PUT.Ypos = binaryReader.ReadInt16(); sb2_PUT.Zpos = binaryReader.ReadInt16(); sb2_PUT.Rot = binaryReader.ReadInt16(); } } binaryReader.BaseStream.Seek((Int64)(8 + 56 * this.header.PatCount), SeekOrigin.Begin); for (Int32 k = 0; k < (Int32)this.header.TypCount; k++) { SB2_MON_PARM sb2_MON_PARM = this.MonAddr[k] = new SB2_MON_PARM(); for (Int32 l = 0; l < 3; l++) { sb2_MON_PARM.Status[l] = (BattleStatus)binaryReader.ReadUInt32(); } sb2_MON_PARM.MaxHP = binaryReader.ReadUInt16(); sb2_MON_PARM.MaxMP = binaryReader.ReadUInt16(); sb2_MON_PARM.WinGil = binaryReader.ReadUInt16(); sb2_MON_PARM.WinExp = binaryReader.ReadUInt16(); for (Int32 m = 0; m < 4; m++) { sb2_MON_PARM.WinItems[m] = binaryReader.ReadByte(); } for (Int32 n = 0; n < 4; n++) { sb2_MON_PARM.StealItems[n] = binaryReader.ReadByte(); } sb2_MON_PARM.Radius = binaryReader.ReadUInt16(); sb2_MON_PARM.Geo = binaryReader.ReadUInt16(); for (Int32 num = 0; num < 6; num++) { sb2_MON_PARM.Mot[num] = binaryReader.ReadUInt16(); } for (Int32 num2 = 0; num2 < 2; num2++) { sb2_MON_PARM.Mesh[num2] = binaryReader.ReadUInt16(); } sb2_MON_PARM.Flags = binaryReader.ReadUInt16(); sb2_MON_PARM.AP = binaryReader.ReadUInt16(); SB2_ELEMENT sb2_ELEMENT = sb2_MON_PARM.Element = new SB2_ELEMENT(); sb2_ELEMENT.dex = binaryReader.ReadByte(); sb2_ELEMENT.str = binaryReader.ReadByte(); sb2_ELEMENT.mgc = binaryReader.ReadByte(); sb2_ELEMENT.wpr = binaryReader.ReadByte(); sb2_ELEMENT.pad = binaryReader.ReadByte(); sb2_ELEMENT.trans = binaryReader.ReadByte(); sb2_ELEMENT.cur_capa = binaryReader.ReadByte(); sb2_ELEMENT.max_capa = binaryReader.ReadByte(); for (Int32 num3 = 0; num3 < 4; num3++) { sb2_MON_PARM.Attr[num3] = binaryReader.ReadByte(); } sb2_MON_PARM.Level = binaryReader.ReadByte(); sb2_MON_PARM.Category = binaryReader.ReadByte(); sb2_MON_PARM.HitRate = binaryReader.ReadByte(); sb2_MON_PARM.P_DP = binaryReader.ReadByte(); sb2_MON_PARM.P_AV = binaryReader.ReadByte(); sb2_MON_PARM.M_DP = binaryReader.ReadByte(); sb2_MON_PARM.M_AV = binaryReader.ReadByte(); sb2_MON_PARM.Blue = binaryReader.ReadByte(); for (Int32 num4 = 0; num4 < 4; num4++) { sb2_MON_PARM.Bone[num4] = binaryReader.ReadByte(); } sb2_MON_PARM.DieSfx = binaryReader.ReadUInt16(); sb2_MON_PARM.Konran = binaryReader.ReadByte(); sb2_MON_PARM.MesCnt = binaryReader.ReadByte(); for (Int32 num5 = 0; num5 < 6; num5++) { sb2_MON_PARM.IconBone[num5] = binaryReader.ReadByte(); } for (Int32 num6 = 0; num6 < 6; num6++) { sb2_MON_PARM.IconY[num6] = binaryReader.ReadSByte(); } for (Int32 num7 = 0; num7 < 6; num7++) { sb2_MON_PARM.IconZ[num7] = binaryReader.ReadSByte(); } sb2_MON_PARM.StartSfx = binaryReader.ReadUInt16(); sb2_MON_PARM.ShadowX = binaryReader.ReadUInt16(); sb2_MON_PARM.ShadowZ = binaryReader.ReadUInt16(); sb2_MON_PARM.ShadowBone = binaryReader.ReadByte(); sb2_MON_PARM.Card = binaryReader.ReadByte(); sb2_MON_PARM.ShadowOfsX = binaryReader.ReadInt16(); sb2_MON_PARM.ShadowOfsZ = binaryReader.ReadInt16(); sb2_MON_PARM.ShadowBone2 = binaryReader.ReadByte(); sb2_MON_PARM.Pad0 = binaryReader.ReadByte(); sb2_MON_PARM.Pad1 = binaryReader.ReadUInt16(); sb2_MON_PARM.Pad2 = binaryReader.ReadUInt16(); } binaryReader.BaseStream.Seek((Int64)(8 + 56 * this.header.PatCount + 116 * this.header.TypCount), SeekOrigin.Begin); for (Int32 num8 = 0; num8 < (Int32)this.header.AtkCount; num8++) { AA_DATA aa_DATA = this.atk[num8] = new AA_DATA(); BattleCommandInfo cmd_INFO = aa_DATA.Info = new BattleCommandInfo(); UInt32 input = binaryReader.ReadUInt32(); Byte b = 0; cmd_INFO.Target = (TargetType)BitUtil.ReadBits(input, ref b, 4); cmd_INFO.DefaultAlly = BitUtil.ReadBits(input, ref b, 1) != 0; cmd_INFO.DisplayStats = (TargetDisplay)BitUtil.ReadBits(input, ref b, 3); cmd_INFO.VfxIndex = (Int16)BitUtil.ReadBits(input, ref b, 9); /*cmd_INFO.sfx_no = (Int16)*/ BitUtil.ReadBits(input, ref b, 12); cmd_INFO.ForDead = BitUtil.ReadBits(input, ref b, 1) != 0; cmd_INFO.DefaultCamera = BitUtil.ReadBits(input, ref b, 1) != 0; cmd_INFO.DefaultOnDead = BitUtil.ReadBits(input, ref b, 1) != 0; BTL_REF btl_REF = aa_DATA.Ref = new BTL_REF(); btl_REF.ScriptId = binaryReader.ReadByte(); btl_REF.Power = binaryReader.ReadByte(); btl_REF.Elements = binaryReader.ReadByte(); btl_REF.Rate = binaryReader.ReadByte(); aa_DATA.Category = binaryReader.ReadByte(); aa_DATA.AddNo = binaryReader.ReadByte(); aa_DATA.MP = binaryReader.ReadByte(); aa_DATA.Type = binaryReader.ReadByte(); aa_DATA.Vfx2 = binaryReader.ReadUInt16(); aa_DATA.Name = binaryReader.ReadUInt16().ToString(); } } }
private int LabelOffset() { return(KEY_BUFFER_OFFSET + BitUtil.Align(KeyBufferLength(), BitUtil.SIZE_OF_INT)); }
internal virtual void AddWord(int wordNum, byte word) { Debug.Assert(wordNum > lastWordNum); Debug.Assert(word != 0); if (!reverse) { if (lastWordNum == -1) { clean = 2 + wordNum; // special case for the 1st sequence dirtyWords.WriteByte(word); } else { switch (wordNum - lastWordNum) { case 1: if (word == 0xFF && (byte)dirtyWords.Bytes[dirtyWords.Length - 1] == 0xFF) { --dirtyWords.Length; WriteSequence(); reverse = true; clean = 2; } else { dirtyWords.WriteByte(word); } break; case 2: dirtyWords.WriteByte(0); dirtyWords.WriteByte(word); break; default: WriteSequence(); clean = wordNum - lastWordNum - 1; dirtyWords.WriteByte(word); break; } } } else { Debug.Assert(lastWordNum >= 0); switch (wordNum - lastWordNum) { case 1: if (word == 0xFF) { if (dirtyWords.Length == 0) { ++clean; } else if ((byte)dirtyWords.Bytes[dirtyWords.Length - 1] == 0xFF) { --dirtyWords.Length; WriteSequence(); clean = 2; } else { dirtyWords.WriteByte(word); } } else { dirtyWords.WriteByte(word); } break; case 2: dirtyWords.WriteByte(0); dirtyWords.WriteByte(word); break; default: WriteSequence(); reverse = false; clean = wordNum - lastWordNum - 1; dirtyWords.WriteByte(word); break; } } lastWordNum = wordNum; cardinality += BitUtil.BitCount(word); }
public override object GetValue(Stream inputStream) { return(BitUtil.ZeroTerminatedString(inputStream)); }
public override object GetValue(Stream inputStream) { return(BitUtil.ToInt32(inputStream)); }
// // Shift // protected uint PerformShift(ShiftType shiftType, uint operand, int shift, bool isZeroSpecialCase, bool setConditionCodes) { switch (shiftType) { case ShiftType.LogicalLeft: // LSL if (!isZeroSpecialCase) { if (setConditionCodes) { CurrentStatus.Carry = BitUtil.IsBitSet(operand, 32 - shift); } // C# takes the shift amount as (right-hand operand & 0x1F), so any value 32 or higher will be treated as 0. // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/bitwise-and-shift-operators if (shift >= 32) { operand = 0; } else { operand <<= shift; } } break; case ShiftType.LogicalRight: // LSR if (isZeroSpecialCase) { if (setConditionCodes) { CurrentStatus.Carry = BitUtil.IsBitSet(operand, 31); } operand = 0; } else { if (setConditionCodes) { CurrentStatus.Carry = BitUtil.IsBitSet(operand, shift - 1); } if (shift >= 32) { operand = 0; } else { operand >>= shift; } } break; case ShiftType.ArithmaticRight: // ASR if (isZeroSpecialCase || shift >= 32) { bool msb = BitUtil.IsBitSet(operand, 31); if (msb) { operand = 0xFFFFFFFF; } else { operand = 0x00000000; } if (setConditionCodes) { CurrentStatus.Carry = msb; } } else { if (setConditionCodes) { CurrentStatus.Carry = BitUtil.IsBitSet(operand, shift - 1); } // C# will do an ASR if the left operand is an int operand = (uint)((int)operand >> shift); } break; case ShiftType.RotateRight: // ROR if (isZeroSpecialCase) { // This operation is like RRX#1. See here for a diagram: // http://www-mdp.eng.cam.ac.uk/web/library/enginfo/mdp_micro/lecture4/lecture4-3-4.html bool oldCarry = CurrentStatus.Carry; CurrentStatus.Carry = BitUtil.IsBitSet(operand, 0); operand >>= 1; if (oldCarry) { BitUtil.SetBit(ref operand, 31); } else { BitUtil.ClearBit(ref operand, 31); } } else { if (setConditionCodes) { CurrentStatus.Carry = BitUtil.IsBitSet(operand, shift - 1); } operand = BitUtil.RotateRight(operand, shift); } break; } return(operand); }
// // Addition/Subtraction helpers // // Thanks to mGBA for easy shortcuts. // include/mgba/internal/arm/isa-inlines.h // // Additional notes on Overflow flag: // http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt // protected void SetCarryAndOverflowOnAddition(uint first, uint second, uint result) { CurrentStatus.Carry = (BitUtil.GetBit(first, 31) + BitUtil.GetBit(second, 31)) > BitUtil.GetBit(result, 31); CurrentStatus.Overflow = !BitUtil.IsBitSet(first ^ second, 31) && BitUtil.IsBitSet(first ^ result, 31); }
private static short *InitSizes() { var allocSize = Unsafe.SizeOf <short>() * 256 + 64; // Never free until process dies. var ptr = Marshal.AllocHGlobal(allocSize); (new Span <byte>((void *)ptr, allocSize)).Clear(); var alignedPtr = (IntPtr)BitUtil.Align((long)ptr, 64); var sizes = (short *)alignedPtr; #region Known fixed-size scalar types // ReSharper disable once PossibleNullReferenceException sizes[(byte)TypeEnum.None] = 0; sizes[(byte)TypeEnum.Int8] = (short)Unsafe.SizeOf <sbyte>(); sizes[(byte)TypeEnum.Int16] = (short)Unsafe.SizeOf <short>(); sizes[(byte)TypeEnum.Int32] = (short)Unsafe.SizeOf <int>(); sizes[(byte)TypeEnum.Int64] = (short)Unsafe.SizeOf <long>(); sizes[(byte)TypeEnum.Int128] = 16; sizes[(byte)TypeEnum.UInt8] = (short)Unsafe.SizeOf <byte>(); sizes[(byte)TypeEnum.UInt16] = (short)Unsafe.SizeOf <ushort>(); sizes[(byte)TypeEnum.UInt32] = (short)Unsafe.SizeOf <uint>(); sizes[(byte)TypeEnum.UInt64] = (short)Unsafe.SizeOf <ulong>(); sizes[(byte)TypeEnum.UInt128] = 16; sizes[(byte)TypeEnum.Float16] = 2; sizes[(byte)TypeEnum.Float32] = (short)Unsafe.SizeOf <float>(); sizes[(byte)TypeEnum.Float64] = (short)Unsafe.SizeOf <double>(); sizes[(byte)TypeEnum.Float128] = 16; sizes[(byte)TypeEnum.Decimal32] = 4; sizes[(byte)TypeEnum.Decimal64] = 8; sizes[(byte)TypeEnum.Decimal128] = 16; sizes[(byte)TypeEnum.Decimal] = 16; sizes[(byte)TypeEnum.SmallDecimal] = SmallDecimal.Size; sizes[(byte)TypeEnum.Bool] = 1; sizes[(byte)TypeEnum.Utf16Char] = 2; sizes[(byte)TypeEnum.UUID] = 16; sizes[(byte)TypeEnum.DateTime] = 8; sizes[(byte)TypeEnum.Timestamp] = Timestamp.Size; sizes[(byte)TypeEnum.Symbol] = Symbol.Size; sizes[(byte)TypeEnum.Symbol32] = Symbol32.Size; sizes[(byte)TypeEnum.Symbol64] = Symbol64.Size; sizes[(byte)TypeEnum.Symbol128] = Symbol128.Size; sizes[(byte)TypeEnum.Symbol256] = Symbol256.Size; #endregion Known fixed-size scalar types for (int i = 1; i <= 31; i++) { if (unchecked ((uint)sizes[i]) > 16) { ThrowHelper.FailFast($"Sizes[{i}] == {sizes[i]} > 16"); } } for (int i = 64; i <= 127; i++) { sizes[i] = -1; } for (int i = 1; i <= TypeEnumOrFixedSize.MaxFixedSize; i++) { sizes[TypeEnumOrFixedSize.MaxTypeEnum + i] = (byte)(i); } return(sizes); }
/// <summary> /// Determines if the input type is flagged (as the there are multiple flags) /// </summary> /// <param name="eFlag">Flag to check for</param> /// <returns>true if the flag bit is 1, false otherwise</returns> public bool IsFlaggedAs(System.Enum eFlag) { return(BitUtil.IsFlagged(Flags, eFlag)); }
public long Position() { var resultingOffset = BitUtil.Align(TermOffset + FrameLength, FrameDescriptor.FRAME_ALIGNMENT); return(LogBufferDescriptor.ComputePosition(TermId, resultingOffset, _positionBitsToShift, _initialTermId)); }
public Result Initialize(UIntPtr address, nuint size, nuint blockSize, int orderMax) { Assert.SdkRequires(FreeLists == null); Assert.SdkRequiresNotEqual(address, UIntPtr.Zero); Assert.SdkRequiresAligned(address.ToUInt64(), (int)BufferAlignment); Assert.SdkRequiresGreaterEqual(blockSize, BlockSizeMin); Assert.SdkRequires(BitUtil.IsPowerOfTwo(blockSize)); Assert.SdkRequiresGreaterEqual(size, blockSize); Assert.SdkRequiresGreater(orderMax, 0); Assert.SdkRequiresLess(orderMax, OrderUpperLimit); // Set up our basic member variables BlockSize = blockSize; OrderMax = orderMax; HeapStart = address; HeapSize = size; TotalFreeSize = 0; // Determine page sizes nuint maxPageSize = BlockSize << OrderMax; nuint maxPageCount = (nuint)Alignment.AlignUp(HeapSize, (uint)maxPageSize) / maxPageSize; Assert.SdkGreater((int)maxPageCount, 0); // Setup the free lists if (ExternalFreeLists != null) { Assert.SdkAssert(InternalFreeLists == null); FreeLists = ExternalFreeLists; } else { InternalFreeLists = GC.AllocateArray <PageList>(OrderMax + 1, true); FreeLists = (PageList *)Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(InternalFreeLists)); if (InternalFreeLists == null) { return(ResultFs.AllocationMemoryFailedInFileSystemBuddyHeapA.Log()); } } // All but the last page region should go to the max order. for (nuint i = 0; i < maxPageCount - 1; i++) { PageEntry *pageEntry = GetPageEntryFromAddress(HeapStart + i * maxPageSize); FreeLists[orderMax].PushBack(pageEntry); } TotalFreeSize += (nuint)FreeLists[orderMax].GetSize() * GetBytesFromOrder(orderMax); // Allocate remaining space to smaller orders as possible. { nuint remaining = HeapSize - (maxPageCount - 1) * maxPageSize; nuint curAddress = HeapStart - (maxPageCount - 1) * maxPageSize; Assert.SdkAligned(remaining, (int)BlockSize); do { // Determine what order we can use. int order = GetOrderFromBytes(remaining + 1); if (order < 0) { Assert.SdkEqual(OrderMax, GetOrderFromBytes(remaining)); order = OrderMax + 1; } Assert.SdkGreater(order, 0); Assert.SdkLessEqual(order, OrderMax + 1); // Add to the correct free list. FreeLists[order - 1].PushBack(GetPageEntryFromAddress(curAddress)); TotalFreeSize += GetBytesFromOrder(order - 1); // Move on to the next order. nuint pageSize = GetBytesFromOrder(order - 1); curAddress += pageSize; remaining -= pageSize; } while (BlockSize <= remaining); } return(Result.Success); }
private int SourceIdentityOffset() { int alignedLength = BitUtil.Align(_buffer.GetInt(_offset + LOG_FILE_NAME_OFFSET), BitUtil.SIZE_OF_INT); return(LOG_FILE_NAME_OFFSET + BitUtil.SIZE_OF_INT + alignedLength); }
private void UpdatePathNodeFlagsUI(bool updateCheckboxes, bool updateUpDowns) { var flags0 = CurrentPathNode?.Flags0.Value ?? 0; var flags1 = CurrentPathNode?.Flags1.Value ?? 0; var flags2 = CurrentPathNode?.Flags2.Value ?? 0; var flags3 = CurrentPathNode?.Flags3.Value ?? 0; var flags4 = CurrentPathNode?.Flags4.Value ?? 0; var flags5 = (uint)(CurrentPathNode?.LinkCountUnk ?? 0); if (updateCheckboxes) { PathNodeFlags01CheckBox.Checked = BitUtil.IsBitSet(flags0, 0); PathNodeFlags02CheckBox.Checked = BitUtil.IsBitSet(flags0, 1); PathNodeFlags03CheckBox.Checked = BitUtil.IsBitSet(flags0, 2); PathNodeFlags04CheckBox.Checked = BitUtil.IsBitSet(flags0, 3); PathNodeFlags05CheckBox.Checked = BitUtil.IsBitSet(flags0, 4); PathNodeFlags06CheckBox.Checked = BitUtil.IsBitSet(flags0, 5); PathNodeFlags07CheckBox.Checked = BitUtil.IsBitSet(flags0, 6); PathNodeFlags08CheckBox.Checked = BitUtil.IsBitSet(flags0, 7); PathNodeFlags11CheckBox.Checked = BitUtil.IsBitSet(flags1, 0); PathNodeFlags12CheckBox.Checked = BitUtil.IsBitSet(flags1, 1); PathNodeFlags13CheckBox.Checked = BitUtil.IsBitSet(flags1, 2); PathNodeFlags14CheckBox.Checked = BitUtil.IsBitSet(flags1, 3); PathNodeFlags15CheckBox.Checked = BitUtil.IsBitSet(flags1, 4); PathNodeFlags16CheckBox.Checked = BitUtil.IsBitSet(flags1, 5); PathNodeFlags17CheckBox.Checked = BitUtil.IsBitSet(flags1, 6); PathNodeFlags18CheckBox.Checked = BitUtil.IsBitSet(flags1, 7); PathNodeFlags21CheckBox.Checked = BitUtil.IsBitSet(flags2, 0); PathNodeFlags22CheckBox.Checked = BitUtil.IsBitSet(flags2, 1); PathNodeFlags23CheckBox.Checked = BitUtil.IsBitSet(flags2, 2); PathNodeFlags24CheckBox.Checked = BitUtil.IsBitSet(flags2, 3); PathNodeFlags25CheckBox.Checked = BitUtil.IsBitSet(flags2, 4); PathNodeFlags26CheckBox.Checked = BitUtil.IsBitSet(flags2, 5); PathNodeFlags27CheckBox.Checked = BitUtil.IsBitSet(flags2, 6); PathNodeFlags28CheckBox.Checked = BitUtil.IsBitSet(flags2, 7); PathNodeFlags31CheckBox.Checked = BitUtil.IsBitSet(flags3, 0); PathNodeFlags32UpDown.Value = (flags3 >> 1) & 127; PathNodeFlags41CheckBox.Checked = BitUtil.IsBitSet(flags4, 0); PathNodeFlags42UpDown.Value = (flags4 >> 1) & 7; PathNodeFlags45CheckBox.Checked = BitUtil.IsBitSet(flags4, 4); PathNodeFlags46CheckBox.Checked = BitUtil.IsBitSet(flags4, 5); PathNodeFlags47CheckBox.Checked = BitUtil.IsBitSet(flags4, 6); PathNodeFlags48CheckBox.Checked = BitUtil.IsBitSet(flags4, 7); PathNodeFlags51CheckBox.Checked = BitUtil.IsBitSet(flags5, 0); PathNodeFlags52CheckBox.Checked = BitUtil.IsBitSet(flags5, 1); PathNodeFlags53CheckBox.Checked = BitUtil.IsBitSet(flags5, 2); } if (updateUpDowns) { PathNodeFlags0UpDown.Value = flags0; PathNodeFlags1UpDown.Value = flags1; PathNodeFlags2UpDown.Value = flags2; PathNodeFlags3UpDown.Value = flags3; PathNodeFlags4UpDown.Value = flags4; PathNodeFlags5UpDown.Value = flags5; } var n = CurrentPathNode; if (n != null) { PathNodeFlags0Label.Text = n.Flags0.ToHexString(); PathNodeFlags1Label.Text = n.Flags1.ToHexString(); PathNodeFlags2Label.Text = n.Flags2.ToHexString(); PathNodeFlags3Label.Text = n.Flags3.ToHexString(); PathNodeFlags4Label.Text = n.Flags4.ToHexString(); } else { PathNodeFlags0Label.Text = "0x00"; PathNodeFlags1Label.Text = "0x00"; PathNodeFlags2Label.Text = "0x00"; PathNodeFlags3Label.Text = "0x00"; PathNodeFlags4Label.Text = "0x00"; } }
/// <summary> /// Peek for new messages in a stream by scanning forward from an initial position. If new messages are found then /// they will be delivered to the <seealso cref="IControlledFragmentHandler"/> up to a limited position. /// /// Use a <seealso cref="ControlledFragmentAssembler"/> to assemble messages which span multiple fragments. Scans must also /// start at the beginning of a message so that the assembler is reset. /// /// </summary> /// <param name="initialPosition"> from which to peek forward. </param> /// <param name="fragmentHandler"> to which message fragments are delivered. </param> /// <param name="limitPosition"> up to which can be scanned. </param> /// <returns> the resulting position after the scan terminates which is a complete message. </returns> /// <seealso cref="ControlledFragmentAssembler"/> /// <seealso cref="ImageControlledFragmentAssembler"/> public virtual long ControlledPeek(long initialPosition, IControlledFragmentHandler fragmentHandler, long limitPosition) { if (_isClosed) { return(0); } ValidatePosition(initialPosition); int initialOffset = (int)initialPosition & _termLengthMask; int offset = initialOffset; long position = initialPosition; UnsafeBuffer termBuffer = ActiveTermBuffer(initialPosition); int capacity = termBuffer.Capacity; _header.Buffer = termBuffer; long resultingPosition = initialPosition; try { do { int length = FrameDescriptor.FrameLengthVolatile(termBuffer, offset); if (length <= 0) { break; } int frameOffset = offset; var alignedLength = BitUtil.Align(length, FrameDescriptor.FRAME_ALIGNMENT); offset += alignedLength; if (FrameDescriptor.IsPaddingFrame(termBuffer, frameOffset)) { continue; } _header.Offset = frameOffset; var action = fragmentHandler.OnFragment( termBuffer, frameOffset + DataHeaderFlyweight.HEADER_LENGTH, length - DataHeaderFlyweight.HEADER_LENGTH, _header); if (action == ControlledFragmentHandlerAction.ABORT) { break; } position += (offset - initialOffset); initialOffset = offset; if ((_header.Flags & FrameDescriptor.END_FRAG_FLAG) == FrameDescriptor.END_FRAG_FLAG) { resultingPosition = position; } if (action == ControlledFragmentHandlerAction.BREAK) { break; } } while (position < limitPosition && offset < capacity); } catch (Exception t) { _errorHandler(t); } return(resultingPosition); }
private void SetPathNodeFlagsFromCheckBoxes() { if (populatingui) { return; } if (CurrentPathNode == null) { return; } uint flags0 = 0; uint flags1 = 0; uint flags2 = 0; uint flags3 = 0; uint flags4 = 0; uint flags5 = 0; flags0 = BitUtil.UpdateBit(flags0, 0, PathNodeFlags01CheckBox.Checked); flags0 = BitUtil.UpdateBit(flags0, 1, PathNodeFlags02CheckBox.Checked); flags0 = BitUtil.UpdateBit(flags0, 2, PathNodeFlags03CheckBox.Checked); flags0 = BitUtil.UpdateBit(flags0, 3, PathNodeFlags04CheckBox.Checked); flags0 = BitUtil.UpdateBit(flags0, 4, PathNodeFlags05CheckBox.Checked); flags0 = BitUtil.UpdateBit(flags0, 5, PathNodeFlags06CheckBox.Checked); flags0 = BitUtil.UpdateBit(flags0, 6, PathNodeFlags07CheckBox.Checked); flags0 = BitUtil.UpdateBit(flags0, 7, PathNodeFlags08CheckBox.Checked); flags1 = BitUtil.UpdateBit(flags1, 0, PathNodeFlags11CheckBox.Checked); flags1 = BitUtil.UpdateBit(flags1, 1, PathNodeFlags12CheckBox.Checked); flags1 = BitUtil.UpdateBit(flags1, 2, PathNodeFlags13CheckBox.Checked); flags1 = BitUtil.UpdateBit(flags1, 3, PathNodeFlags14CheckBox.Checked); flags1 = BitUtil.UpdateBit(flags1, 4, PathNodeFlags15CheckBox.Checked); flags1 = BitUtil.UpdateBit(flags1, 5, PathNodeFlags16CheckBox.Checked); flags1 = BitUtil.UpdateBit(flags1, 6, PathNodeFlags17CheckBox.Checked); flags1 = BitUtil.UpdateBit(flags1, 7, PathNodeFlags18CheckBox.Checked); flags2 = BitUtil.UpdateBit(flags2, 0, PathNodeFlags21CheckBox.Checked); flags2 = BitUtil.UpdateBit(flags2, 1, PathNodeFlags22CheckBox.Checked); flags2 = BitUtil.UpdateBit(flags2, 2, PathNodeFlags23CheckBox.Checked); flags2 = BitUtil.UpdateBit(flags2, 3, PathNodeFlags24CheckBox.Checked); flags2 = BitUtil.UpdateBit(flags2, 4, PathNodeFlags25CheckBox.Checked); flags2 = BitUtil.UpdateBit(flags2, 5, PathNodeFlags26CheckBox.Checked); flags2 = BitUtil.UpdateBit(flags2, 6, PathNodeFlags27CheckBox.Checked); flags2 = BitUtil.UpdateBit(flags2, 7, PathNodeFlags28CheckBox.Checked); flags3 = BitUtil.UpdateBit(flags3, 0, PathNodeFlags31CheckBox.Checked); flags3 += (((uint)PathNodeFlags32UpDown.Value & 127u) << 1); flags4 = BitUtil.UpdateBit(flags4, 0, PathNodeFlags41CheckBox.Checked); flags4 += (((uint)PathNodeFlags42UpDown.Value & 7u) << 1); flags4 = BitUtil.UpdateBit(flags4, 4, PathNodeFlags45CheckBox.Checked); flags4 = BitUtil.UpdateBit(flags4, 5, PathNodeFlags46CheckBox.Checked); flags4 = BitUtil.UpdateBit(flags4, 6, PathNodeFlags47CheckBox.Checked); flags4 = BitUtil.UpdateBit(flags4, 7, PathNodeFlags48CheckBox.Checked); flags5 = BitUtil.UpdateBit(flags5, 0, PathNodeFlags51CheckBox.Checked); flags5 = BitUtil.UpdateBit(flags5, 1, PathNodeFlags52CheckBox.Checked); flags5 = BitUtil.UpdateBit(flags5, 2, PathNodeFlags53CheckBox.Checked); lock (ProjectForm.ProjectSyncRoot) { if (CurrentPathNode.Flags0.Value != flags0) { CurrentPathNode.Flags0 = (byte)flags0; ProjectForm.SetYndHasChanged(true); } if (CurrentPathNode.Flags1.Value != flags1) { CurrentPathNode.Flags1 = (byte)flags1; ProjectForm.SetYndHasChanged(true); } if (CurrentPathNode.Flags2.Value != flags2) { CurrentPathNode.Flags2 = (byte)flags2; ProjectForm.SetYndHasChanged(true); } if (CurrentPathNode.Flags3.Value != flags3) { CurrentPathNode.Flags3 = (byte)flags3; ProjectForm.SetYndHasChanged(true); } if (CurrentPathNode.Flags4.Value != flags4) { CurrentPathNode.Flags4 = (byte)flags4; ProjectForm.SetYndHasChanged(true); } if (CurrentPathNode.LinkCountUnk != flags5) { CurrentPathNode.LinkCountUnk = (byte)flags5; ProjectForm.SetYndHasChanged(true); } } populatingui = true; UpdatePathNodeFlagsUI(false, true); //update updowns populatingui = false; }
public int AppendFragmentedMessage( int termId, int termOffset, HeaderWriter header, DirectBufferVector[] vectors, int length, int maxPayloadLength, ReservedValueSupplier reservedValueSupplier) { int numMaxPayloads = length / maxPayloadLength; int remainingPayload = length % maxPayloadLength; int lastFrameLength = remainingPayload > 0 ? BitUtil.Align(remainingPayload + DataHeaderFlyweight.HEADER_LENGTH, FrameDescriptor.FRAME_ALIGNMENT) : 0; int requiredLength = (numMaxPayloads * (maxPayloadLength + DataHeaderFlyweight.HEADER_LENGTH)) + lastFrameLength; UnsafeBuffer termBuffer = _termBuffer; int termLength = termBuffer.Capacity; int resultingOffset = termOffset + requiredLength; PutRawTailOrdered(termId, resultingOffset); if (resultingOffset > termLength) { resultingOffset = HandleEndOfLogCondition(termBuffer, termOffset, header, termLength, termId); } else { int frameOffset = termOffset; byte flags = FrameDescriptor.BEGIN_FRAG_FLAG; int remaining = length; int vectorIndex = 0; int vectorOffset = 0; do { int bytesToWrite = Math.Min(remaining, maxPayloadLength); int frameLength = bytesToWrite + DataHeaderFlyweight.HEADER_LENGTH; int alignedLength = BitUtil.Align(frameLength, FrameDescriptor.FRAME_ALIGNMENT); header.Write(termBuffer, frameOffset, frameLength, termId); int bytesWritten = 0; int payloadOffset = frameOffset + DataHeaderFlyweight.HEADER_LENGTH; do { var vector = vectors[vectorIndex]; int vectorRemaining = vector.length - vectorOffset; int numBytes = Math.Min(bytesToWrite - bytesWritten, vectorRemaining); termBuffer.PutBytes(payloadOffset, vector.buffer, vector.offset + vectorOffset, numBytes); bytesWritten += numBytes; payloadOffset += numBytes; vectorOffset += numBytes; if (vectorRemaining <= numBytes) { vectorIndex++; vectorOffset = 0; } } while (bytesWritten < bytesToWrite); if (remaining <= maxPayloadLength) { flags |= FrameDescriptor.END_FRAG_FLAG; } FrameDescriptor.FrameFlags(termBuffer, frameOffset, flags); if (null != reservedValueSupplier) { long reservedValue = reservedValueSupplier(termBuffer, frameOffset, frameLength); termBuffer.PutLong(frameOffset + DataHeaderFlyweight.RESERVED_VALUE_OFFSET, reservedValue, ByteOrder.LittleEndian); } FrameDescriptor.FrameLengthOrdered(termBuffer, frameOffset, frameLength); flags = 0; frameOffset += alignedLength; remaining -= bytesToWrite; } while (remaining > 0); } return(resultingOffset); }
private void SetPathNodeLinkFlagsFromCheckBoxes() { if (populatingui) { return; } if (CurrentPathLink == null) { return; } uint flags0 = 0; uint flags1 = 0; uint flags2 = 0; flags0 = BitUtil.UpdateBit(flags0, 0, PathNodeLinkFlags01CheckBox.Checked); flags0 = BitUtil.UpdateBit(flags0, 1, PathNodeLinkFlags02CheckBox.Checked); flags0 += (((uint)PathNodeLinkFlags03UpDown.Value & 7u) << 2); flags0 += (((uint)PathNodeLinkFlags04UpDown.Value & 7u) << 5); flags1 = BitUtil.UpdateBit(flags1, 0, PathNodeLinkFlags11CheckBox.Checked); flags1 = BitUtil.UpdateBit(flags1, 1, PathNodeLinkFlags12CheckBox.Checked); flags1 = BitUtil.UpdateBit(flags1, 2, PathNodeLinkFlags13CheckBox.Checked); flags1 = BitUtil.UpdateBit(flags1, 3, PathNodeLinkFlags14CheckBox.Checked); flags1 += (((uint)PathNodeLinkOffsetSizeUpDown.Value & 7u) << 4); flags1 = BitUtil.UpdateBit(flags1, 7, PathNodeLinkFlags18CheckBox.Checked); flags2 = BitUtil.UpdateBit(flags2, 0, PathNodeLinkFlags21CheckBox.Checked); flags2 = BitUtil.UpdateBit(flags2, 1, PathNodeLinkFlags22CheckBox.Checked); flags2 += (((uint)PathNodeLinkBackLanesUpDown.Value & 7u) << 2); flags2 += (((uint)PathNodeLinkFwdLanesUpDown.Value & 7u) << 5); bool updgfx = false; lock (ProjectForm.ProjectSyncRoot) { if (CurrentPathLink.Flags0.Value != flags0) { CurrentPathLink.Flags0 = (byte)flags0; ProjectForm.SetYndHasChanged(true); } if (CurrentPathLink.Flags1.Value != flags1) { CurrentPathLink.Flags1 = (byte)flags1; ProjectForm.SetYndHasChanged(true); updgfx = true; } if (CurrentPathLink.Flags2.Value != flags2) { CurrentPathLink.Flags2 = (byte)flags2; ProjectForm.SetYndHasChanged(true); updgfx = true; } } populatingui = true; UpdatePathNodeLinkFlagsUI(false, true); //update updowns populatingui = false; if (updgfx && (ProjectForm.WorldForm != null) && (CurrentYndFile != null)) { ProjectForm.WorldForm.UpdatePathYndGraphics(CurrentYndFile, false); } }
/// <summary> /// Construct a buffer builder with an initial capacity that will be rounded up to the nearest power of 2. /// </summary> /// <param name="initialCapacity"> at which the capacity will start. </param> public BufferBuilder(int initialCapacity) { _capacity = BitUtil.FindNextPositivePowerOfTwo(initialCapacity); _buffer = new byte[_capacity]; _mutableDirectBuffer = new UnsafeBuffer(_buffer); }
public void LzcntNegative() { Assert.AreEqual(0, BitUtil.NumberOfLeadingZeros(-1)); Console.WriteLine(BitUtil.NumberOfLeadingZeros(-1)); }
public long AppendFragmentedMessage(HeaderWriter header, UnsafeBuffer srcBuffer, int srcOffset, int length, int maxPayloadLength, ReservedValueSupplier reservedValueSupplier) { int numMaxPayloads = length / maxPayloadLength; int remainingPayload = length % maxPayloadLength; int lastFrameLength = remainingPayload > 0 ? BitUtil.Align(remainingPayload + DataHeaderFlyweight.HEADER_LENGTH, FrameDescriptor.FRAME_ALIGNMENT) : 0; int requiredLength = (numMaxPayloads * (maxPayloadLength + DataHeaderFlyweight.HEADER_LENGTH)) + lastFrameLength; long rawTail = GetAndAddRawTail(requiredLength); int termId = LogBufferDescriptor.TermId(rawTail); long termOffset = rawTail & 0xFFFFFFFFL; UnsafeBuffer termBuffer = _termBuffer; int termLength = termBuffer.Capacity; long resultingOffset = termOffset + requiredLength; if (resultingOffset > termLength) { resultingOffset = HandleEndOfLogCondition(termBuffer, termOffset, header, termLength, termId); } else { int offset = (int)termOffset; byte flags = FrameDescriptor.BEGIN_FRAG_FLAG; int remaining = length; do { int bytesToWrite = Math.Min(remaining, maxPayloadLength); int frameLength = bytesToWrite + DataHeaderFlyweight.HEADER_LENGTH; int alignedLength = BitUtil.Align(frameLength, FrameDescriptor.FRAME_ALIGNMENT); header.Write(termBuffer, offset, frameLength, termId); termBuffer.PutBytes(offset + DataHeaderFlyweight.HEADER_LENGTH, srcBuffer, srcOffset + (length - remaining), bytesToWrite); if (remaining <= maxPayloadLength) { flags |= FrameDescriptor.END_FRAG_FLAG; } FrameDescriptor.FrameFlags(termBuffer, offset, flags); if (null != reservedValueSupplier) { long reservedValue = reservedValueSupplier(termBuffer, offset, frameLength); termBuffer.PutLong(offset + DataHeaderFlyweight.RESERVED_VALUE_OFFSET, reservedValue); } FrameDescriptor.FrameLengthOrdered(termBuffer, offset, frameLength); flags = 0; offset += alignedLength; remaining -= bytesToWrite; } while (remaining > 0); } return(resultingOffset); }
public override int Step() { uint instruction = Cpu.MemoryMap.ReadU16(Reg(PC)); Reg(PC) += 2; int type = BitUtil.GetBitRange(instruction, 13, 15); switch (type) { case 0b000: if (BitUtil.GetBitRange(instruction, 11, 12) == 0b11) { return(FormTwoAddSubtractOperation(instruction)); } else { return(FormOneMoveShiftedRegister(instruction)); } case 0b001: return(FormThreeAluOperation(instruction)); case 0b010: if (BitUtil.IsBitSet(instruction, 12)) { return(FormSevenEightLoadStore(instruction)); } else if (BitUtil.IsBitSet(instruction, 11)) { return(FormSixPcRelativeLoad(instruction)); } else if (BitUtil.IsBitSet(instruction, 10)) { return(FormFiveRegisterOperations(instruction)); } else { return(FormFourAluOperation(instruction)); } case 0b011: return(FormNineLoadStore(instruction)); case 0b100: if (BitUtil.IsBitSet(instruction, 12)) { return(FormElevenLoadStore(instruction)); } else { return(FormTenLoadStore(instruction)); } case 0b101: if (BitUtil.IsBitSet(instruction, 12)) { int subtype = BitUtil.GetBitRange(instruction, 9, 10); switch (subtype) { case 0b00: return(FormThirteenAddSpOffset(instruction)); case 0b10: if (BitUtil.IsBitSet(instruction, 11)) { return(FormFourteenPopOperation(instruction)); } else { return(FormFourteenPushOperation(instruction)); } } } else { return(FormTwelveAddPcSp(instruction)); } break; case 0b110: if (BitUtil.IsBitSet(instruction, 12)) { if (BitUtil.GetBitRange(instruction, 8, 11) == 0b1111) { return(FormSeventeenSwiOperation(instruction)); } else { return(FormSixteenConditionalBranch(instruction)); } } else { return(FormFifteenBlockTransfer(instruction)); } case 0b111: int opcode = BitUtil.GetBitRange(instruction, 11, 12); switch (opcode) { case 0b00: return(FormEighteenUnconditionalBranch(instruction)); case 0b10: return(FormNineteenLoadHiBits(instruction)); case 0b11: return(FormNineteenExecuteBranch(instruction)); } break; } InterpreterAssert($"Invalid instruction ({instruction:x4})"); return(0); }
public RetainableMemoryPool(Func <RetainableMemoryPool <T>, int, RetainableMemory <T> > factory, int minLength = DefaultMinBufferLength, int maxLength = DefaultMaxBufferLength, int maxBuffersPerBucketPerCore = DefaultMaxNumberOfBuffersPerBucketPerCore, int maxBucketsToTry = DefaultMaxBucketsToTry, bool rentAlwaysClean = false) { if (factory == null) { throw new ArgumentNullException(nameof(factory)); } lock (KnownPools) { // Start from 2, other code depends on the first 2 items being null. // pool idx == 0 is always null which means a buffer is not from pool // pool idx == 1 means a buffer is from default pool, e.g. static array pool for (int i = 2; i < KnownPools.Length; i++) { if (KnownPools[i] == null) { PoolIdx = checked ((byte)i); KnownPools[i] = this; break; } } if (PoolIdx == 0) { ThrowHelper.ThrowInvalidOperationException("KnownPools slots exhausted. 64 pools ought to be enough for anybody."); } } IsRentAlwaysClean = rentAlwaysClean; Factory = (length) => { var memory = factory(this, length); if (IsRentAlwaysClean) { memory.GetSpan().Clear(); } AtomicCounter.Dispose(ref memory.CounterRef); ThrowHelper.DebugAssert(memory.IsPooled); return(memory); }; if (minLength <= 16) { minLength = 16; } _minBufferLengthPow2 = 32 - BitUtil.NumberOfLeadingZeros(minLength - 1); MinBufferLength = 1 << _minBufferLengthPow2; if (maxBucketsToTry < 0) { maxBucketsToTry = 0; } MaxBucketsToTry = maxBucketsToTry; if (maxLength <= 0) { throw new ArgumentOutOfRangeException(nameof(maxLength)); } if (maxBuffersPerBucketPerCore < 0) { throw new ArgumentOutOfRangeException(nameof(maxBuffersPerBucketPerCore)); } // Our bucketing algorithm has a min length of 2^4 and a max length of 2^30. // Constrain the actual max used to those values. const int maximumBufferLength = 0x40000000; if (maxLength > maximumBufferLength) { maxLength = maximumBufferLength; } else if (maxLength < minLength) { maxLength = minLength; } MaxBufferLength = maxLength; // Create the buckets. int maxBuckets = SelectBucketIndex(maxLength); var buckets = new MemoryBucket[maxBuckets + 1]; for (int i = 0; i < buckets.Length; i++) { buckets[i] = new MemoryBucket(this, GetMaxSizeForBucket(i), maxBuffersPerBucketPerCore); } _buckets = buckets; }
public DataRecord(byte[] data, byte[] header) : base(data, header, true) { RecordNumber = BitUtil.ToInt32(header, 5, false); }