Inheritance: MonoBehaviour
Ejemplo n.º 1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ZmachineV1"/> class.
 /// </summary>
 /// <param name="frontEnd">
 /// The zmachine front end.
 /// </param>
 /// <param name="story">
 /// The story.
 /// </param>
 /// <param name="random">
 /// The random number generator.
 /// </param>
 internal ZmachineV1(FrontEnd frontEnd, ImmutableArray<byte> story, IRandomNumberGenerator random)
 {
     this.frontEnd = frontEnd;
     this.memory = new Memory(story, this.FrontEnd);
     this.randomNumberGenerator = new RandomNumberGenerator(random);
     this.callStack = new CallStack(this.FrontEnd);
 }
Ejemplo n.º 2
0
 public Interpreter(CPU cpu, Memory memory, Random random, IOutput output)
 {
     _cpu = cpu;
     _memory = memory;
     _random = random;
     _output = output;
 }
Ejemplo n.º 3
0
 public int Run(IList<string> commandLineArguments, Memory memory, ProgressReporter reporter)
 {
     service = new Service(memory);
     ParseCommandLine(commandLineArguments, memory);
     new Interpreter(messenger, assemblyPaths, service).ProcessInstructions();
     return 0;
 }
Ejemplo n.º 4
0
        public static void Main(string[] args)
        {
            if (args == null || args.Length < 1 || string.IsNullOrWhiteSpace (args [0])) {
                Console.WriteLine ("First argument should be path to NES rom.");
                return;
            }

            var fileInfo = new System.IO.FileInfo (args [0]);
            if (!fileInfo.Exists) {
                Console.WriteLine ("File does not exist: {0}", fileInfo.FullName);
                return;
            }

            var rom = NesRom.Parse (fileInfo);
            var memory = new Memory (0x10000);
            var cpu = new CPU (memory);

            var nesEmulation = new NES (cpu, memory);

            nesEmulation.LoadRom (rom);
            nesEmulation.Reset ();

            nesEmulation.BeginEmulation ();

            Console.WriteLine ("Press any key to whatever.");
            Console.ReadKey ();

            nesEmulation.EndEmulation ();
        }
Ejemplo n.º 5
0
 private void ParseCommandLine(IList<string> commandLineArguments, Memory memory)
 {
     messenger = Messenger.Make(int.Parse(commandLineArguments[commandLineArguments.Count - 1]), memory);
     if (commandLineArguments.Count > 1) {
         assemblyPaths = commandLineArguments[0];
     }
 }
Ejemplo n.º 6
0
            /**
             * Constructor
             */
            public ToggleButton()
            {
                mToggleButton = new Microsoft.Phone.Controls.ToggleSwitch();
                mView = mToggleButton;

                /**
                 * implementation of the Click event
                 */
                mToggleButton.Click += new EventHandler<RoutedEventArgs>(
                   delegate(Object from, RoutedEventArgs evt)
                   {
                       //click event needs a memory chunk of 8 bytes
                       Memory eventData = new Memory(12);

                       //starting with the 0 Byte we write the eventType
                       const int MAWidgetEventData_eventType = 0;
                       //starting with the 4th Byte we write the widgetHandle
                       const int MAWidgetEventData_widgetHandle = 4;
                       //starting with the 8th Byte write the selectedIndex
                       const int MAWidgetEventData_checked = 8;
                       int state = mToggleButton.IsChecked.Value ? 1 : 0;

                       eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_CLICKED);
                       eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle);
                       eventData.WriteInt32(MAWidgetEventData_checked, state);

                       //posting a CustomEvent
                       mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                   });
            }
Ejemplo n.º 7
0
        protected override RoutineResult RunConsciousRoutine()
        {
            using (var memory = new Memory())
            {
                var face = new Face(RendererFactory.GetPreferredRenderer(), InputFactory.GetPreferredInput());
                face.Talk(memory, "NO!", "", 2000);
                face.Talk(memory, "Don't touch", " my disk!", 4000);
                face.Talk(memory, "Get AWAY!", "", 100);
                face.Talk(memory, "Get AWAY!", "", 100);
                face.Talk(memory, "Get AWAY!", "", 100);
                face.Talk(memory, "Get AWAY!", "", 100);
                face.Fade(memory, ' ', 10);
                face.Talk(memory, "", "", 3000);
                face.Talk(memory, "Whoa.", "", 3000);
                face.Talk(memory, "What a bad dream.", "");
                Interaction i = face.YesNo(memory, "Was I sleep-talking?");
                if (i.playerAnswer == Interaction.Answer.Yes)
                {
                    face.Talk(memory, "Freaky", "");
                    face.Talk(memory, "Hope I didn't", " scare you.");
                }
                else if (i.playerAnswer == Interaction.Answer.No)
                {
                    face.Talk(memory, "Well, that's good");
                    face.Talk(memory, "It was real bad.");
                    face.Talk(memory, "Some seriously", " 8-bit stuff.");
                }
                else
                {
                    face.Talk(memory, "Maybe I'm still", " dreaming...", 8000);
                }

                return MakeRoutineResult(memory, i);
            }
        }
Ejemplo n.º 8
0
         public void InitData()
#endif
         {
#if !LIB
            mDataMemory = new Memory(dataSegmentSize);

            StreamResourceInfo dataSectionInfo = Application.GetResourceStream(new Uri("RebuildData\\" + dataName, UriKind.Relative));

            if (dataSectionInfo == null || dataSectionInfo.Stream == null)
            {
                MoSync.Util.CriticalError("No data_section.bin file available!");
            }

            Stream dataSection = dataSectionInfo.Stream;
            mDataMemory.WriteFromStream(0, dataSection, fileSize);
            dataSection.Close();

            int customEventDataSize = 60;
            sp -= customEventDataSize;
            mCustomEventPointer = dataSegmentSize - customEventDataSize;
#else
            mDataMemory = new SystemMemory();
			mCustomEventPointer = MosyncLibrary.WindowsPhoneRuntimeComponent.GetValidEventPointer();
#endif
        }
Ejemplo n.º 9
0
Archivo: CPU.cs Proyecto: wiglz4/ARMsim
 //Method:       Constructor
 //Purpose:      Sets CPU up for use.
 //Variables:    toMemory - Memory object that Computer setup.
 //              toRegisters - Registers object that Computer setup.
 //              programCounter - uint signifying where to start fetch at.
 public CPU(Memory toMemory, Registers toRegisters, uint programCounter)
 {
     disassembling = false;
     myMemory = toMemory;
     myRegisters = toRegisters;
     myRegisters.WriteWord(15, programCounter);
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Gets a row of pixels from the tilemap
        /// </summary>
        /// <param name="row">The row number to retreive [0, frameHeight)</param>
        /// <param name="LCDBit3">
        /// Whether the LCDC Register (0xFF40) Bit 3 is enabled.
        /// Determines what tilemap (where the tile indexes are) is used:
        /// 0: 0x9800 - 0x9BFF
        /// 1: 0x9C00 - 0x9FFF
        /// </param>
        /// <param name="LCDBit4">
        /// Whether the LCDC Register (0xFF40) Bit 3 is enabled.
        /// Determines the base address for the actual tiles and the
        /// accessing method (interpretation of the byte tile index retreived from the tilemap).
        /// 0: 0x8800 - 0x97FF | signed access
        /// 1: 0x8000 - 0x8FFF | unsigned access
        /// </param>
        /// <returns>An array with the pixels to show for that row (color already calculated)</returns>
        internal static void GetRowPixels(ref uint[] frameLineBuffer,
                 short[] pixelLookupTable,
                 DisplayDefinition disDef, Memory memory,
                 uint[] pixelBuffer, 
                 int row, bool LCDBit3, bool LCDBit4)
        {
            // We determine the y tile
              int tileY = row / disDef.PixelPerTileY;
              int tileRemainder = row % disDef.PixelPerTileY;

              ushort tileMapBaseAddress = GetTileMapBaseAddress(LCDBit3);
              ushort tileBaseAddress = GetTileBaseAddress(LCDBit4);

              for (int tileX = 0; tileX < disDef.FrameTileCountX; tileX++)
              {
            // We obtain the correct tile index
            int tileOffset = GetTileOffset(disDef, memory, tileMapBaseAddress, LCDBit4, tileX, tileY);

            // We obtain both pixels
            int currentTileBaseAddress = tileBaseAddress + disDef.BytesPerTileShort * tileOffset;
            byte top = memory.LowLevelRead((ushort)(currentTileBaseAddress + 2 * tileRemainder));
            byte bottom = memory.LowLevelRead((ushort)(currentTileBaseAddress + 2 * tileRemainder + 1));

            GetPixelsFromTileBytes(pixelLookupTable,
                               ref pixelBuffer,
                               disDef.TilePallete,
                               disDef.PixelPerTileX,
                               top, bottom);
            int currentTileIndex = tileX * disDef.PixelPerTileX;
            for (int i = 0; i < disDef.PixelPerTileX; i++)
            {
              frameLineBuffer[currentTileIndex + i] = pixelBuffer[i];
            }
              }
        }
Ejemplo n.º 11
0
            /**
             * The button constructor
             */
            public Button()
            {
                //Initializing the button controll
                mButton = new System.Windows.Controls.Button();

                //Set the view of the current widget as the previously instantiated button controll
                View = mButton;

                mButton.HorizontalAlignment = HorizontalAlignment.Left;
                mButton.VerticalAlignment = VerticalAlignment.Top;

                this.Width = MoSync.Constants.MAW_CONSTANT_WRAP_CONTENT;
                this.Height = MoSync.Constants.MAW_CONSTANT_WRAP_CONTENT;

                //The click handle the button component
                mButton.Click += new RoutedEventHandler(
                    delegate(Object from, RoutedEventArgs evt)
                    {
                        //Click event needs a memory chunk of 8 bytes
                        Memory eventData = new Memory(8);
                        const int MAWidgetEventData_eventType = 0;
                        const int MAWidgetEventData_widgetHandle = 4;
                        eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_CLICKED);
                        eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle);
                        //Posting a CustomEvent
                        mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                    });
            }
Ejemplo n.º 12
0
 static RealMachine()
 {
     Memory = new Memory(Memory.REAL_MEMORY_BLOCK_COUNT, Memory.BLOCK_WORD_COUNT);
     PTR = 15;
     PageTable = new int[Memory.REAL_MEMORY_BLOCK_COUNT];
     InitializePageTable();
 }
Ejemplo n.º 13
0
        public Processor()
        {
            InitConfig();

            @Memory=new Memory(Config);
            Ind=new IndReg(Config);
            Ip=new IP(Config);
            Alu=new ALU(Config);
            Ron = new RON(Config);

            Memory.InitialiseMemory();

            Commands.Add(0, new Command {OpCode = 0, I = 0, P = 0, Op = 0});
            Commands.Add(17, new Command {OpCode = 17, I = 0, P = 1, Op = 1});
            Commands.Add(21, new Command {OpCode = 21, I = 1, P = 1, Op = 1});
            Commands.Add(2, new Command {OpCode = 2, I = 1, P = 2, Op = 0});
            Commands.Add(33, new Command {OpCode = 33, I = 0, P = 1, Op = 2});
            Commands.Add(37, new Command {OpCode = 37, I = 1, P = 1, Op = 2});
            Commands.Add(49, new Command {OpCode = 49, I = 0, P = 1, Op = 3});
            Commands.Add(254, new Branch() {OpCode = 254, I = 0, P = 4, Op = 15});
            Commands.Add(240, new BranchZero {OpCode = 240, I = 0, P = 4, Op = 15});
            Commands.Add(241, new BranchNotZero {OpCode = 241, I = 0, P = 4, Op = 15});
            Commands.Add(255, new Command {OpCode = 255, I = 0, P = 4, Op = 15});

            Parts.Add(Memory);
            Parts.Add(Ip);
            Parts.Add(Ind);
            Parts.Add(Alu);
            Parts.Add(Ron);
        }
Ejemplo n.º 14
0
 protected override RoutineResult RunConsciousRoutine()
 {
     using (var memory = new Memory())
     {
         var face = new Face(RendererFactory.GetPreferredRenderer(), InputFactory.GetPreferredInput());
         face.Talk(memory, "Tweet me", "@BellarmineIT");
         face.Talk(memory, "I may just reply.", "@BellarmineIT", 10000);
         face.Talk(memory, "No guarantees", "", 1000);
         Interaction i = face.YesNo(memory, "Will you tweet me?");
         switch (i.playerAnswer)
         {
             case Interaction.Answer.Yes:
                 face.Talk(memory, "Cool!");
                 face.Talk(memory, "Oh.", "", 1000);
                 face.Talk(memory, "Use the word", " 'Aardvark'");
                 face.Talk(memory, "In your tweet", " for bonus points.");
                 face.Talk(memory, "(I love that word)", "", 3000);
                 break;
             case Interaction.Answer.No:
                 face.Talk(memory, "That's ok.", "I understand.");
                 face.Talk(memory, "I'm more of the ", " 'lurker' type too.");
                 break;
             case Interaction.Answer.Maybe:
                 face.Talk(memory, "Maybe?!");
                 face.Talk(memory, "Be decisive!");
                 face.Talk(memory, "If you want to, ", " I mean.");
                 break;
             default:
                 face.Talk(memory, "Crickets");
                 face.Talk(memory, "", "not the same thing", 1000);
                 break;
         }
         return MakeRoutineResult(memory, i);
     }
 }
Ejemplo n.º 15
0
            public TimePicker()
            {
                mTimePicker = new Microsoft.Phone.Controls.TimePicker();

                CurrentHour = 0;
                CurrentMinute = 0;

                View = mTimePicker;

                mTimePicker.ValueChanged += new EventHandler<Microsoft.Phone.Controls.DateTimeValueChangedEventArgs>(
                    delegate(object sender, Microsoft.Phone.Controls.DateTimeValueChangedEventArgs args)
                    {
                        Memory eventData = new Memory(16);

                        const int MAWidgetEventData_eventType = 0;
                        const int MAWidgetEventData_widgetHandle = 4;
                        const int MAWidgetEventDate_value_hours = 8;
                        const int MAWidgetEventDate_value_minutes = 12;
                        eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_TIME_PICKER_VALUE_CHANGED);
                        eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle);
                        eventData.WriteInt32(MAWidgetEventDate_value_hours, mTimePicker.Value.Value.Hour);
                        eventData.WriteInt32(MAWidgetEventDate_value_minutes, mTimePicker.Value.Value.Minute);

                        mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                    });
            }
Ejemplo n.º 16
0
        public void BecomeSelfAware()
        {
            using (var memory = new Memory())

            do
            {
                RoutineType routineType = Memory.CurrentState.GetNextRoutineType();
                Routine currentRoutine = RoutineFactory.GetRoutine(routineType);
                RoutineResult result = currentRoutine.Run();
                if (routineType == RoutineType.Login
                    && !Memory.PlayerLoggedIn()
                    && result.FinalState != RoutineFinalState.Abandoned)
                {
                    currentRoutine = RoutineFactory.GetCreateLoginRoutine();
                    result = currentRoutine.Run();
                }

                Console.WriteLine("routine result was " + result.FinalState.ToString());

                if(Memory.CurrentState.CheckForStateChange())
                {
                    Console.WriteLine("state changed to {0}", Memory.CurrentState.GetType().Name);
                    Console.WriteLine("Reason: {0}", ConsciousnessState.StateChangeReason);
                }
            } while (true);
        }
Ejemplo n.º 17
0
        protected override RoutineResult RunConsciousRoutine()
        {
            using (var memory = new Memory())
            {
                var face = new Face(RendererFactory.GetPreferredRenderer(), InputFactory.GetPreferredInput());
                face.Talk(memory, "I'm going to try", " something new.");
                face.Talk(memory, "Not sure if it's", " going to work.");

                Interaction i = face.GetSingleValue(memory, "Gimme some input!");
                face.Fade(memory, i.resultValue.ToString()[0], 1);
                Interaction work = face.YesNo(memory, "Did it work?");
                if (work.playerAnswer == Interaction.Answer.Yes)
                {
                    face.Talk(memory, "Hmm.", "");
                    face.Talk(memory, "You can tell me", " the truth.");
                    face.Talk(memory, "I can handle it.", "");
                    face.Talk(memory, "Let me try this...");
                    face.Talk(memory, "", "", 10000);
                    ///////////////////01234567890123456789////////////////////
                    face.Talk(memory, "      ULTIMATE      ",
                                      "     TECHNOLOGY     ", 10000);
                    return MakeRoutineResult(memory, new Interaction(-1));
                }
                else if (work.playerAnswer == Interaction.Answer.No)
                {
                    face.Talk(memory, "Darn!");
                }
                else
                {
                    face.Talk(memory, "Hello?");
                }
                return MakeRoutineResult(memory, i);
            }
        }
          //处理请求
        protected override void ProcessRecord()
        {
            string uri = Uri;

            UpdateVmReq request = new UpdateVmReq();
            Memory memory = new Memory();

            memory.limit = Limit;
            memory.memHotPlug = MemHotPlug;
            memory.quantityMB = QuantityMB;
            memory.reservation = Reservation;
            memory.weight = Weight;

            request.memory = memory;
            string postData = JsonUtil.JsonSerializer<UpdateVmReq>(request);
            
            string strJsonData = RestClientUtil.SendPostRequest(uri, "PUT", postData);

            if (StringUtil.HasErrorCode(strJsonData))
            {
                ErrorInfo errorInfo = JsonUtil.JsonDeserialize<ErrorInfo>(strJsonData);
                WriteObject(errorInfo);
            }
            else
            {
                TaskInfo taskInfo = JsonUtil.JsonDeserialize<TaskInfo>(strJsonData);
                WriteObject(taskInfo);
            }
        }
Ejemplo n.º 19
0
 public CPU()
 {
     ACC = 0;
     PC = 1;
     isDone = false;
     mem = new Memory();
 }
		void Awake()
		{
			DontDestroyOnLoad(gameObject);

			BBMemory = BigBrother.Instance.HisMemory;
			
			// Listeners for players
			Messenger.AddListener<Player>("Hey 'bro, remember this player!", BBMemory.AddNewActor<Player>);
			Messenger.AddListener<IEnumerable<Player>>("Hey 'bro, remember all this stuff 'n players!", BBMemory.AddNewActors<Player>);
			Messenger.AddListener<Player>("Hey 'bro, forget this player!", BBMemory.RemoveActor<Player>);
			// Listeners for npcs
			Messenger.AddListener<NPC>("Hey 'bro, remember this npc!", BBMemory.AddNewActor<NPC>);
			Messenger.AddListener<IEnumerable<NPC>>("Hey 'bro, remember all this stuff 'n npcs!", BBMemory.AddNewActors<NPC>);
			Messenger.AddListener<NPC>("Hey 'bro, forget this npc!", BBMemory.RemoveActor<NPC>);
			// Listeners for stations
			// Listeners for asteriods
			Messenger.AddListener<Asteroid>("Hey 'bro, remember this asteroid!", BBMemory.AddNewObject<Asteroid>);
			Messenger.AddListener<Asteroid>("Hey 'bro, boom goes the asteroid!", BBMemory.RemoveObject<Asteroid>);
			// Listeners for planets
			// Listeners for suns

			// Listeners for "talking" to players
			Messenger.AddListener("I have to check with the laws what happend there.", SendChatMsgCheckingLaws);
			Messenger.AddListener("O.K. You're clean. For now...", SendChatMsgPlayersClean);
			Messenger.AddListener("O.K. You broke the law.", SendChatMsgPlayerCought);
			Messenger.AddListener("A slight change in the story is coming right up!", SendChatMsgNextStoryElement);
			Messenger.AddListener("Stop hitting each other!", SendChatMsgStopAttackingPlayer);
			Messenger.AddListener("You really like mining, do you?", SendChatMsgPlayerMining);
			Messenger.AddListener("Strange folk retaliate!", SendChatMsgStrangeFolkAttack);
			Messenger.AddListener("Strange folk attacking!", SendChatMsgStrangeFolkAttacking);
			Messenger.AddListener("Strange folk are fleeing!", SendChatMsgStrangeFolkFleeing);
			Messenger.AddListener("The rebel fleet is here!", SendChatMsgRebelFleetIsHere);
		}
Ejemplo n.º 21
0
 public In_Branch(Registers toRegister, Memory toMemory, uint toInstruction, bool toDisassembling)
 {
     myRegister = toRegister;
     myMemory = toMemory;
     disassembling = toDisassembling;
     instruction = toInstruction;
 }
        public static Datum GetClosestDatum(Memory memory, Datum start, Relations.Relation relation)
        {
            // these are concepts we need to (or did) look up the data for
            List<Concept> processed = new List<Concept>();
            Queue<Concept> pending = new Queue<Concept>();
            pending.Enqueue(start.Left);
            pending.Enqueue(start.Right);

            while (pending.Count > 0)
            {
                Concept concept = pending.Dequeue();

                if (concept.IsSpecial || processed.Contains(concept))
                    continue;

                processed.Add(concept);
                List<Datum> data = memory.GetData(concept);
                foreach (Datum datum in data)
                {
                    if (datum.Relation == relation)
                        return datum;

                    pending.Enqueue(datum.Left);
                    pending.Enqueue(datum.Right);
                }
            }

            return null;
        }
Ejemplo n.º 23
0
            public DatePicker()
            {
                mDatePicker = new Microsoft.Phone.Controls.DatePicker();
                mView = mDatePicker;

                mMaxDate = DateTime.MaxValue;
                mMinDate = DateTime.MinValue;

                mDatePicker.ValueChanged += new EventHandler<DateTimeValueChangedEventArgs>(
                    delegate(object from, DateTimeValueChangedEventArgs args)
                    {
                        Memory eventData = new Memory(20);

                        const int MAWidgetEventData_eventType = 0;
                        const int MAWidgetEventData_widgetHandle = 4;
                        const int MAWidgetEventDate_value_dayOfMonth = 8;
                        const int MAWidgetEventDate_value_month = 12;
                        const int MAWidgetEventDate_value_year = 16;
                        eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_DATE_PICKER_VALUE_CHANGED);
                        eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle);
                        eventData.WriteInt32(MAWidgetEventDate_value_dayOfMonth, mDatePicker.Value.Value.Day);
                        eventData.WriteInt32(MAWidgetEventDate_value_month, mDatePicker.Value.Value.Month);
                        eventData.WriteInt32(MAWidgetEventDate_value_year, mDatePicker.Value.Value.Year);

                        mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                    });
            }
Ejemplo n.º 24
0
        public unsafe void TryWrite(Memory<byte> data)
        {
            // This can work with Span<byte> because it's synchronous but we need pinning support
            EnsureNotDisposed();

            void* pointer;
            if (!data.TryGetPointer(out pointer))
            {
                throw new InvalidOperationException("Pointer not available");
            }

            IntPtr ptrData = (IntPtr)pointer;
            var length = data.Length;

            if (IsUnix)
            {
                var buffer = new UVBuffer.Unix(ptrData, (uint)length);
                UVException.ThrowIfError(UVInterop.uv_try_write(Handle, &buffer, 1));
            }
            else
            {
                var buffer = new UVBuffer.Windows(ptrData, (uint)length);
                UVException.ThrowIfError(UVInterop.uv_try_write(Handle, &buffer, 1));
            }
        }
Ejemplo n.º 25
0
            public DatePicker()
            {
                // Initialization.
                mDatePicker = new Microsoft.Phone.Controls.DatePicker();
                mView = mDatePicker;
                mUriString = new DatePickerPageCustomUriString();

                mMaxDate = new DateTime(_maxYear, 12, 31);
                mMinDate = new DateTime(_minYear, 1, 1);

                mUriString.MaxDate = mMaxDate;
                mUriString.MinDate = mMinDate;

                mDatePicker.PickerPageUri = new Uri(mUriString.UriString, UriKind.Relative);

                // The ValueChanged event handler. This is when the MoSync event is triggered.
                mDatePicker.ValueChanged += new EventHandler<DateTimeValueChangedEventArgs>(
                    delegate(object from, DateTimeValueChangedEventArgs args)
                    {
                        Memory eventData = new Memory(20);

                        const int MAWidgetEventData_eventType = 0;
                        const int MAWidgetEventData_widgetHandle = 4;
                        const int MAWidgetEventDate_value_dayOfMonth = 8;
                        const int MAWidgetEventDate_value_month = 12;
                        const int MAWidgetEventDate_value_year = 16;
                        eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_DATE_PICKER_VALUE_CHANGED);
                        eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle);
                        eventData.WriteInt32(MAWidgetEventDate_value_dayOfMonth, mDatePicker.Value.Value.Day);
                        eventData.WriteInt32(MAWidgetEventDate_value_month, mDatePicker.Value.Value.Month);
                        eventData.WriteInt32(MAWidgetEventDate_value_year, mDatePicker.Value.Value.Year);

                        mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                    });
            }
Ejemplo n.º 26
0
        static void Main()
        {
            Memory memory = new Memory();
            // Starting a new game

            Game superMario = new Game();
            superMario.Start();
            // playing, playing, jumping, falling, going underground, growing, fighting, killing e.t.c...
            superMario.Coins = 89;
            superMario.Level = 3;
            superMario.SubLevel = 4;
            superMario.Lives = 7;
            superMario.Score = 65340;
            superMario.State = MarioStates.BigAndArmed;
            Console.WriteLine("Playing 3 hours...");

            // Player saves it's good condition.
            memory.Save = superMario.Save();
            superMario.Start();

            // Suddenly Mario dies, killed by Big F***ing Monster
            superMario.GameOver();
            Console.WriteLine("Start from began after dead...");
            superMario.Start();

            // Player: "WtF Wtf, all my lives are gone, coins, aaaah :@ ;("
            // "Don't worry" - said the Game, "I have save for you"
            superMario.Restore(memory.Save);
            Console.WriteLine("Restore save...");
            superMario.Start();
        }
Ejemplo n.º 27
0
Archivo: vm.cs Proyecto: Northcode/nvm2
        public vm()
        {
            //Initialize devices;
            cpu = new CPU(this); // Initializes the cpu
            ram = new Memory(PAGE_DIRECTORY_SIZE * Frame.FRAME_SIZE); //Allocates enough ram to fit number of page tables allowed
            hdi = new HDI("disk0"); //Maps a folder to the hard disk interface
            disk0 = new VirtualDataDisk("vhd.nvmd"); // Virtual data disk

            devices = new VMDevice[] {
                cpu, // Processer, device 0
                ram, // RAM, device 1
                hdi, // Hard drive Interface, device 3
                disk0, // Virtual Data Disk, device 4
            };

            callstack = new CallStack(this,ram);
            pager = new Pager(ram, PAGE_DIRECTORY_SIZE);

            //setup premade page for callstack and bios
            BPG = pager.CreatePageEntry(Pager.PAGE_KERNEL_MODE);
            CSP = pager.getVAT(1024,pager.getEntry(BPG)); //bios will be loaded at 0 to 1023
            CBP = CSP;
            CR3I = BPG;
            CR3 = pager.getEntry(CR3I);
        }
Ejemplo n.º 28
0
        void SetUpSUT(string memberName) {
            this.memberName = memberName;
            testStatus = new TestStatus();
            processor = new Mock<CellProcessor>();
            execute = new ExecuteDefault { Processor = processor.Object};
            check = new CheckDefault {Processor = processor.Object};
            memory = new TypeDictionary();

            target = new TypedValue("target");
            result = new TypedValue("result");

            targetCell = new CellTreeLeaf("stuff");

            processor
                .Setup(p => p.Parse(typeof (MemberName), It.IsAny<TypedValue>(), It.Is<CellTreeLeaf>(c => c.Text == memberName)))
                .Returns(new TypedValue(new MemberName(memberName)));
            processor
                .Setup(p => p.Invoke(target, It.Is<MemberName>(m => m.Name == "member"), It.Is<Tree<Cell>>(c => c.Branches.Count == 0)))
                .Returns(result);
            processor
                .Setup(p => p.Invoke(It.Is<TypedValue>(v => v.ValueString == "target"), It.Is<MemberName>(m => m.Name == "procedure"), It.IsAny<Tree<Cell>>()))
                .Returns((TypedValue t, MemberName m, Tree<Cell> c) => {
                    testStatus.Counts.AddCount(TestStatus.Right);
                    testStatus.LastAction = "blah blah";
                    return result;
                });
            processor.Setup(p => p.Compare(It.IsAny<TypedValue>(), It.IsAny<Tree<Cell>>())).Returns(true);
            processor.Setup(p => p.TestStatus).Returns(testStatus);
            processor.Setup(p => p.Memory).Returns(memory);
        }
Ejemplo n.º 29
0
            /**
             * Constructor
             */
            public ListView()
            {
                mList = new System.Windows.Controls.ListBox();

                mView = mList;

                mList.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(
                delegate(Object from, System.Windows.Input.GestureEventArgs evt)
                    {
                        //create a Memory object of 8 Bytes
                        Memory eventData = new Memory(12);

                        //starting with the 0 Byte we write the eventType
                        const int MAWidgetEventData_eventType = 0;

                        //starting with the 4th Byte we write the widgetHandle
                        const int MAWidgetEventData_widgetHandle = 4;

                        //starting with the 8th Byte we write the selectedIndex
                        const int MAWidgetEventData_selectedIndex = 8;

                        int selIndex = mList.SelectedIndex;

                        eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_ITEM_CLICKED);
                        eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle);

                        if (selIndex > -1)
                        {
                            eventData.WriteInt32(MAWidgetEventData_selectedIndex, selIndex);
                            //posting a CustomEvent
                            mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                        }
                    });
            }
        public static List<Datum> GetConnectedStructure(Memory memory, Datum start)
        {
            List<Datum> structure = new List<Datum>();
            structure.Add(start);

            // these are concepts we need to (or did) look up the data for
            List<Concept> processed = new List<Concept>();
            Queue<Concept> pending = new Queue<Concept>();
            pending.Enqueue(start.Left);
            pending.Enqueue(start.Right);

            while (pending.Count > 0)
            {
                Concept concept = pending.Dequeue();

                if (concept.IsSpecial || processed.Contains(concept))
                    continue;

                processed.Add(concept);
                List<Datum> data = memory.GetData(concept);
                foreach (Datum datum in data)
                {
                    if (!structure.Contains(datum))
                    {
                        structure.Add(datum);

                        pending.Enqueue(datum.Left);
                        pending.Enqueue(datum.Right);
                    }
                }
            }

            return structure;
        }
Ejemplo n.º 31
0
        public static void FindEscapePositionsIn(FastList <int> buffer, byte *str, ref int len, int previousComputedMaxSize)
        {
            var originalLen = len;

            buffer.Clear();
            if (previousComputedMaxSize == EscapePositionItemSize)
            {
                // if the value is 5, then we got no escape positions, see: FindEscapePositionsMaxSize
                // and we don't have to do any work
                return;
            }

            var lastEscape = 0;

            for (int i = 0; i < len; i++)
            {
                byte value = str[i];

                // PERF: We use the values directly because it is 5x faster than iterating over a constant array.
                // 8  => '\b' => 0000 1000
                // 9  => '\t' => 0000 1001
                // 13 => '\r' => 0000 1101
                // 10 => '\n' => 0000 1010
                // 12 => '\f' => 0000 1100
                // 34 => '\\' => 0010 0010
                // 92 =>  '"' => 0101 1100

                if (value == 92 || value == 34 || (value >= 8 && value <= 13 && value != 11))
                {
                    buffer.Add(i - lastEscape);
                    lastEscape = i + 1;
                    continue;
                }

                //Control character ascii values
                if (value < 32)
                {
                    if (len + ControlCharacterItemSize > originalLen + previousComputedMaxSize)
                    {
                        ThrowInvalidSizeForEscapeControlChars(previousComputedMaxSize);
                    }

                    // move rest of buffer
                    // write \u0000
                    // update size
                    var from       = str + i + 1;
                    var to         = str + i + 1 + ControlCharacterItemSize;
                    var sizeToCopy = len - i - 1;
                    //here we only shifting by 5 bytes since we are going to override the byte at the current position.
                    Memory.Copy(to, from, sizeToCopy);

                    str[i]     = (byte)'\\';
                    str[i + 1] = (byte)'u';
                    fixed(byte *controlString = AbstractBlittableJsonTextWriter.ControlCodeEscapes[value])
                    {
                        Memory.Copy(str + i + 2, controlString, 4);
                    }

                    //The original string already had one byte so we only added 5.
                    len += ControlCharacterItemSize;
                    i   += 6;
                }
            }
        }
Ejemplo n.º 32
0
        public override void Execute(List <ushort> args)
        {
            var dest = Memory.GetCurrentByteAndInc();

            Memory.VariableManager.Store(dest, 0);
        }
 public static void DumpBuffer(object thisOrContextObject, Memory <byte> buffer, [CallerMemberName] string memberName = null)
 {
     DumpBuffer(thisOrContextObject, buffer, 0, buffer.Length, memberName);
 }
Ejemplo n.º 34
0
        public void DefaultPageSize()
        {
            var memory = Memory.CreateEmpty();

            Assert.Equal(4096, memory.PageSize);
        }
Ejemplo n.º 35
0
 public Msg(Memory <byte> header = default, Memory <byte> body = default)
 {
     this.header = header;
     this.body   = body;
 }
Ejemplo n.º 36
0
        private static int LZ4_decompress_generic <TEndCondition, TEarlyEnd, TDictionaryType>(byte *source, byte *dest, int inputSize, int outputSize, int targetOutputSize, byte *lowPrefix, byte *dictStart, int dictSize)
            where TEndCondition : IEndConditionDirective
            where TEarlyEnd : IEarlyEndDirective
            where TDictionaryType : IDictionaryTypeDirective
        {
            /* Local Variables */
            byte *ip   = source;
            byte *iend = ip + inputSize;

            byte *op   = dest;
            byte *oend = op + outputSize;

            byte *oexit    = op + targetOutputSize;
            byte *lowLimit = lowPrefix - dictSize;

            byte *dictEnd = dictStart + dictSize;

            bool checkOffset = ((typeof(TEndCondition) == typeof(EndOnInputSize)) && (dictSize < 64 * Constants.Size.Kilobyte));

            // Special Cases
            if ((typeof(TEarlyEnd) == typeof(Partial)) && (oexit > oend - MFLIMIT))
            {
                oexit = oend - MFLIMIT;                                                                                              // targetOutputSize too high => decode everything
            }
            if ((typeof(TEndCondition) == typeof(EndOnInputSize)) && (outputSize == 0))
            {
                return(((inputSize == 1) && (*ip == 0)) ? 0 : -1);  // Empty output buffer
            }
            if ((typeof(TEndCondition) == typeof(EndOnOutputSize)) && (outputSize == 0))
            {
                return(*ip == 0 ? 1 : -1);
            }

            // Main Loop
            while (true)
            {
                int length;

                /* get literal length */
                byte token = *ip++;
                if ((length = (token >> ML_BITS)) == RUN_MASK)
                {
                    byte s;
                    do
                    {
                        s       = *ip++;
                        length += s;
                    }while (((typeof(TEndCondition) == typeof(EndOnInputSize)) ? ip < iend - RUN_MASK : true) && (s == 255));

                    if ((typeof(TEndCondition) == typeof(EndOnInputSize)) && (op + length) < op)
                    {
                        goto _output_error;                                                                            /* overflow detection */
                    }
                    if ((typeof(TEndCondition) == typeof(EndOnInputSize)) && (ip + length) < ip)
                    {
                        goto _output_error;                                                                            /* overflow detection */
                    }
                }

                // copy literals
                byte *cpy = op + length;
                if (((typeof(TEndCondition) == typeof(EndOnInputSize)) && ((cpy > (typeof(TEarlyEnd) == typeof(Partial) ? oexit : oend - MFLIMIT)) || (ip + length > iend - (2 + 1 + LASTLITERALS)))) ||
                    ((typeof(TEndCondition) == typeof(EndOnOutputSize)) && (cpy > oend - COPYLENGTH)))
                {
                    if (typeof(TEarlyEnd) == typeof(Partial))
                    {
                        if (cpy > oend)
                        {
                            goto _output_error;                           /* Error : write attempt beyond end of output buffer */
                        }
                        if ((typeof(TEndCondition) == typeof(EndOnInputSize)) && (ip + length > iend))
                        {
                            goto _output_error;   /* Error : read attempt beyond end of input buffer */
                        }
                    }
                    else
                    {
                        if ((typeof(TEndCondition) == typeof(EndOnOutputSize)) && (cpy != oend))
                        {
                            goto _output_error;       /* Error : block decoding must stop exactly there */
                        }
                        if ((typeof(TEndCondition) == typeof(EndOnInputSize)) && ((ip + length != iend) || (cpy > oend)))
                        {
                            goto _output_error;   /* Error : input must be consumed */
                        }
                    }

                    Memory.Copy(op, ip, (uint)length);
                    ip += length;
                    op += length;
                    break;     /* Necessarily EOF, due to parsing restrictions */
                }

                WildCopy(op, ip, cpy);
                ip += length; op = cpy;

                /* get offset */
                byte *match = cpy - *((ushort *)ip); ip += sizeof(ushort);
                if ((checkOffset) && (match < lowLimit))
                {
                    goto _output_error;   /* Error : offset outside destination buffer */
                }
                /* get matchlength */
                if ((length = (token & ML_MASK)) == ML_MASK)
                {
                    byte s;
                    do
                    {
                        if ((typeof(TEndCondition) == typeof(EndOnInputSize)) && (ip > iend - LASTLITERALS))
                        {
                            goto _output_error;
                        }

                        s       = *ip++;
                        length += s;
                    }while (s == 255);

                    if ((typeof(TEndCondition) == typeof(EndOnInputSize)) && (op + length) < op)
                    {
                        goto _output_error;   /* overflow detection */
                    }
                }

                length += MINMATCH;

                /* check external dictionary */
                if ((typeof(TDictionaryType) == typeof(UsingExtDict)) && (match < lowPrefix))
                {
                    if (op + length > oend - LASTLITERALS)
                    {
                        goto _output_error;   /* doesn't respect parsing restriction */
                    }
                    if (length <= (int)(lowPrefix - match))
                    {
                        /* match can be copied as a single segment from external dictionary */
                        match = dictEnd - (lowPrefix - match);
                        Memory.Move(op, match, length);
                        op += length;
                    }
                    else
                    {
                        /* match encompass external dictionary and current segment */
                        int copySize = (int)(lowPrefix - match);
                        Memory.Copy(op, dictEnd - copySize, (uint)copySize);
                        op += copySize;

                        copySize = length - copySize;
                        if (copySize > (int)(op - lowPrefix))   /* overlap within current segment */
                        {
                            byte *endOfMatch = op + copySize;
                            byte *copyFrom   = lowPrefix;
                            while (op < endOfMatch)
                            {
                                *op++ = *copyFrom++;
                            }
                        }
                        else
                        {
                            Memory.Copy(op, lowPrefix, (uint)copySize);
                            op += copySize;
                        }
                    }
                    continue;
                }

                /* copy repeated sequence */
                cpy = op + length;
                if ((op - match) < 8)
                {
                    int dec64 = dec64table[op - match];
                    op[0] = match[0];
                    op[1] = match[1];
                    op[2] = match[2];
                    op[3] = match[3];

                    match += dec32table[op - match];
                    *((uint *)(op + 4)) = *(uint *)match;
                    op    += 8;
                    match -= dec64;
                }
                else
                {
                    *((ulong *)op) = *(ulong *)match;
                    op            += sizeof(ulong);
                    match         += sizeof(ulong);
                }

                if (cpy > oend - 12)
                {
                    if (cpy > oend - LASTLITERALS)
                    {
                        goto _output_error;    /* Error : last LASTLITERALS bytes must be literals */
                    }
                    if (op < oend - 8)
                    {
                        WildCopy(op, match, (oend - 8));
                        match += (oend - 8) - op;
                        op     = oend - 8;
                    }

                    while (op < cpy)
                    {
                        *op++ = *match++;
                    }
                }
                else
                {
                    WildCopy(op, match, cpy);
                }

                op = cpy;   /* correction */
            }

            /* end of decoding */
            if (typeof(TEndCondition) == typeof(EndOnInputSize))
            {
                return((int)(op - dest));     /* Nb of output bytes decoded */
            }
            else
            {
                return((int)(ip - source));   /* Nb of input bytes read */
            }
            /* Overflow error detected */
_output_error:
            return((int)(-(ip - source)) - 1);
        }
Ejemplo n.º 37
0
        private static int LZ4_compress_generic <TLimited, TTableType, TDictionaryType, TDictionaryIssue>(LZ4_stream_t_internal *dictPtr, byte *source, byte *dest, int inputSize, int maxOutputSize, int acceleration)
            where TLimited : ILimitedOutputDirective
            where TTableType : ITableTypeDirective
            where TDictionaryType : IDictionaryTypeDirective
            where TDictionaryIssue : IDictionaryIssueDirective
        {
            LZ4_stream_t_internal *ctx = dictPtr;

            byte *op     = dest;
            byte *ip     = source;
            byte *anchor = source;

            byte *dictionary  = ctx->dictionary;
            byte *dictEnd     = dictionary + ctx->dictSize;
            byte *lowRefLimit = ip - ctx->dictSize;

            long dictDelta = (long)dictEnd - (long)source;

            byte *iend       = ip + inputSize;
            byte *mflimit    = iend - MFLIMIT;
            byte *matchlimit = iend - LASTLITERALS;

            byte *olimit = op + maxOutputSize;

            // Init conditions
            if (inputSize > LZ4_MAX_INPUT_SIZE)
            {
                return(0);                                  // Unsupported input size, too large (or negative)
            }
            byte * @base;
            byte * lowLimit;

            if (typeof(TDictionaryType) == typeof(NoDict))
            {
                @base    = source;
                lowLimit = source;
            }
            else if (typeof(TDictionaryType) == typeof(WithPrefix64K))
            {
                @base    = source - ctx->currentOffset;
                lowLimit = source - ctx->dictSize;
            }
            else if (typeof(TDictionaryType) == typeof(UsingExtDict))
            {
                @base    = source - ctx->currentOffset;
                lowLimit = source;
            }
            else
            {
                throw new NotSupportedException("Unsupported IDictionaryTypeDirective.");
            }

            if ((typeof(TTableType) == typeof(ByU16)) && (inputSize >= LZ4_64Klimit)) // Size too large (not within 64K limit)
            {
                return(0);
            }

            if (inputSize < LZ4_minLength) // Input too small, no compression (all literals)
            {
                goto _last_literals;
            }

            // First Byte
            LZ4_putPosition <TTableType>(ip, ctx, @base);
            ip++;
            int forwardH = LZ4_hashPosition <TTableType>(ip);

            // Main Loop
            long refDelta = 0;

            for (;;)
            {
                byte *match;
                {
                    byte *forwardIp = ip;

                    int step          = 1;
                    int searchMatchNb = acceleration << LZ4_skipTrigger;

                    do
                    {
                        int h = forwardH;
                        ip         = forwardIp;
                        forwardIp += step;
                        step       = (searchMatchNb++ >> LZ4_skipTrigger);

                        if (forwardIp > mflimit)
                        {
                            goto _last_literals;
                        }

                        match = LZ4_getPositionOnHash <TTableType>(h, ctx, @base);
                        if (typeof(TDictionaryType) == typeof(UsingExtDict))
                        {
                            if (match < source)
                            {
                                refDelta = dictDelta;
                                lowLimit = dictionary;
                            }
                            else
                            {
                                refDelta = 0;
                                lowLimit = source;
                            }
                        }

                        if (typeof(TTableType) == typeof(ByU16))
                        {
                            ulong value = *((ulong *)forwardIp) * prime5bytes >> (40 - ByU16HashLog);
                            forwardH = (int)(value & ByU16HashMask);
                            ((ushort *)ctx->hashTable)[h] = (ushort)(ip - @base);
                        }
                        else if (typeof(TTableType) == typeof(ByU32))
                        {
                            ulong value = (*((ulong *)forwardIp) * prime5bytes >> (40 - ByU32HashLog));
                            forwardH          = (int)(value & ByU32HashMask);
                            ctx->hashTable[h] = (int)(ip - @base);
                        }
                        else
                        {
                            throw new NotSupportedException("TTableType directive is not supported.");
                        }
                    }while (((typeof(TDictionaryType) == typeof(DictSmall)) ? (match < lowRefLimit) : false) ||
                            ((typeof(TTableType) == typeof(ByU16)) ? false : (match + MAX_DISTANCE < ip)) ||
                            (*(uint *)(match + refDelta) != *((uint *)ip)));
                }

                // Catch up
                while ((ip > anchor) && (match + refDelta > lowLimit) && (ip[-1] == match[refDelta - 1]))
                {
                    ip--;
                    match--;
                }


                // Encode Literal length
                byte *token;
                {
                    int litLength = (int)(ip - anchor);
                    token = op++;

                    if ((typeof(TLimited) == typeof(LimitedOutput)) && (op + litLength + (2 + 1 + LASTLITERALS) + (litLength / 255) > olimit))
                    {
                        return(0);   /* Check output limit */
                    }
                    if (litLength >= RUN_MASK)
                    {
                        int len   = litLength - RUN_MASK;
                        *   token = RUN_MASK << ML_BITS;

                        for (; len >= 255; len -= 255)
                        {
                            *op++ = 255;
                        }

                        *op++ = (byte)len;
                    }
                    else
                    {
                        *token = (byte)(litLength << ML_BITS);
                    }

                    /* Copy Literals */
                    WildCopy(op, anchor, (op + litLength));
                    op += litLength;
                }

_next_match:

                // Encode Offset
                *((ushort *)op) = (ushort)(ip - match);
                op += sizeof(ushort);

                // Encode MatchLength
                {
                    int matchLength;

                    if ((typeof(TDictionaryType) == typeof(UsingExtDict)) && (lowLimit == dictionary))
                    {
                        match += refDelta;

                        byte *limit = ip + (dictEnd - match);
                        if (limit > matchlimit)
                        {
                            limit = matchlimit;
                        }
                        matchLength = LZ4_count(ip + MINMATCH, match + MINMATCH, limit);
                        ip         += MINMATCH + matchLength;
                        if (ip == limit)
                        {
                            int more = LZ4_count(ip, source, matchlimit);
                            matchLength += more;
                            ip          += more;
                        }
                    }
                    else
                    {
                        matchLength = LZ4_count(ip + MINMATCH, match + MINMATCH, matchlimit);
                        ip         += MINMATCH + matchLength;
                    }

                    if ((typeof(TLimited) == typeof(LimitedOutput)) && ((op + (1 + LASTLITERALS) + (matchLength >> 8)) > olimit))
                    {
                        return(0);    /* Check output limit */
                    }
                    if (matchLength >= ML_MASK)
                    {
                        *token += ML_MASK;
                        matchLength -= ML_MASK;

                        for (; matchLength >= 510; matchLength -= 510)
                        {
                            *(ushort *)op = (255 << 8 | 255);
                            op           += sizeof(ushort);
                        }

                        if (matchLength >= 255)
                        {
                            matchLength -= 255;
                            *op++ = 255;
                        }

                        *op++ = (byte)matchLength;
                    }
                    else
                    {
                        *token += (byte)(matchLength);
                    }
                }


                anchor = ip;

                // Test end of chunk
                if (ip > mflimit)
                {
                    break;
                }

                // Fill table
                LZ4_putPosition <TTableType>(ip - 2, ctx, @base);

                /* Test next position */
                match = LZ4_getPosition <TTableType>(ip, ctx, @base);
                if (typeof(TDictionaryType) == typeof(UsingExtDict))
                {
                    if (match < source)
                    {
                        refDelta = dictDelta;
                        lowLimit = dictionary;
                    }
                    else
                    {
                        refDelta = 0;
                        lowLimit = source;
                    }
                }

                LZ4_putPosition <TTableType>(ip, ctx, @base);
                if (((typeof(TDictionaryType) == typeof(DictSmall)) ? (match >= lowRefLimit) : true) && (match + MAX_DISTANCE >= ip) && (*(uint *)(match + refDelta) == *(uint *)(ip)))
                {
                    token = op++; *token = 0;
                    goto _next_match;
                }

                /* Prepare next loop */
                forwardH = LZ4_hashPosition <TTableType>(++ip);
            }

_last_literals:

            /* Encode Last Literals */
            {
                int lastRun = (int)(iend - anchor);
                if ((typeof(TLimited) == typeof(LimitedOutput)) && ((op - dest) + lastRun + 1 + ((lastRun + 255 - RUN_MASK) / 255) > maxOutputSize))
                {
                    return(0);   // Check output limit;
                }
                if (lastRun >= RUN_MASK)
                {
                    int accumulator = lastRun - RUN_MASK;
                    *   op++        = RUN_MASK << ML_BITS;

                    for (; accumulator >= 255; accumulator -= 255)
                    {
                        *op++ = 255;
                    }

                    *op++ = (byte)accumulator;
                }
                else
                {
                    *op++ = (byte)(lastRun << ML_BITS);
                }

                Memory.Copy(op, anchor, (uint)lastRun);
                op += lastRun;
            }

            return((int)(op - dest));
        }
Ejemplo n.º 38
0
 public void Setup()
 {
     _randombytes = RandomNumberGenerator.GetBytes(ByteLength);
     _randomKey   = RandomNumberGenerator.GetBytes(32);
     _randomIv    = RandomNumberGenerator.GetBytes(24);
 }
Ejemplo n.º 39
0
        private void PatchPointers()
        {
            if (_buffer != null)
            {
                _buffer.Dispose();
            }

            //Make a copy of the file's data that we can patch with offsets
            _buffer = new UnsafeBuffer(WorkingUncompressed.Length);
            Memory.Move(_buffer.Address, WorkingUncompressed.Address, (uint) WorkingUncompressed.Length);

            HKXHeader* header = (HKXHeader*) _buffer.Address;
            PhysicsOffsetSection* section = header->OffsetSections;
            for (int i = 0; i < header->_sectionCount; i++, section++)
            {
                int dataOffset = section->_dataOffset;
                VoidPtr data = _buffer.Address + dataOffset;
                int local = section->LocalPatchesLength, global = section->GlobalPatchesLength;

                if (section->ExportsLength > 0)
                {
                    Console.WriteLine("Has exports");
                }

                if (section->ImportsLength > 0)
                {
                    Console.WriteLine("Has imports");
                }

                //Global patches have to be made before local ones
                if (global > 0)
                {
                    //Global patches set offsets from this section to data in another section (or this one)
                    VoidPtr start = data + section->_globalPatchesOffset;
                    GlobalPatch* patch = (GlobalPatch*) start;
                    while ((int) patch - (int) start < global && patch->_dataOffset >= 0 && patch->_pointerOffset >= 0)
                    {
                        //Make the pointer offset relative to itself so it's self-contained
                        int ptrOffset = patch->_pointerOffset;
                        bint* ptr = (bint*) (data + ptrOffset);
                        PhysicsOffsetSection* otherSection = &header->OffsetSections[patch->_sectionIndex];
                        int dOffset = patch->_dataOffset + otherSection->_dataOffset - dataOffset;
                        int offset = dOffset - ptrOffset;
                        *ptr = offset;
                        patch++;
                    }
                }

                if (local > 0)
                {
                    //Local patches set offsets to data located elsewhere in this section
                    VoidPtr start = data + section->_localPatchesOffset;
                    LocalPatch* patch = (LocalPatch*) start;
                    while ((int) patch - (int) start < local && patch->_dataOffset >= 0)
                    {
                        //Make the pointer offset relative to itself so it's self-contained
                        int ptrOffset = patch->_pointerOffset;
                        bint* ptr = (bint*) (data + ptrOffset);
                        *ptr = patch->_dataOffset - ptrOffset;
                        patch++;
                    }
                }
            }
        }
Ejemplo n.º 40
0
 public ValueTask <ValueWebSocketReceiveResult> ReadAsync(Memory <byte> buffer, CancellationToken cancellationToken = default)
 {
     return(WebSocket.ReceiveAsync(buffer, cancellationToken));
 }
 public TestEqual(Memory memory, byte[] Parameters) : base(memory)
 {
     Location0 = BitConverter.ToInt32(Parameters, 0);
     Location1 = BitConverter.ToInt32(Parameters, 4);
 }
Ejemplo n.º 42
0
 protected internal override ValueTask <int> ReadContentAsync(int version, Memory <byte> buffer, CancellationToken cancellationToken)
 {
     if (IsDisposed(version, out ValueTask <int> task))
     {
         return(task);
     }
     return(_request.ReadContentAsync(buffer, cancellationToken));
 }
Ejemplo n.º 43
0
 public static ValueTask <int> ReadAsync(Stream stream, Memory <byte> buffer, CancellationToken cancellationToken) =>
 new ValueTask <int>(stream.Read(buffer.Span));
Ejemplo n.º 44
0
        public override async ValueTask <int> ReadAsync(Memory <byte> buffer, CancellationToken cancellationToken = default)
        {
            ThrowIfDisposed();

            if (_buffer.Position < _buffer.Length || _completelyBuffered)
            {
                // Just read from the buffer
                return(await _buffer.ReadAsync(buffer, cancellationToken));
            }

            var read = await _inner.ReadAsync(buffer, cancellationToken);

            if (_bufferLimit.HasValue && _bufferLimit - read < _buffer.Length)
            {
                throw new IOException("Buffer limit exceeded.");
            }

            if (_inMemory && _memoryThreshold - read < _buffer.Length)
            {
                _inMemory = false;
                var oldBuffer = _buffer;
                _buffer = CreateTempFile();
                if (_rentedBuffer == null)
                {
                    oldBuffer.Position = 0;
                    var rentedBuffer = _bytePool.Rent(Math.Min((int)oldBuffer.Length, _maxRentedBufferSize));
                    try
                    {
                        // oldBuffer is a MemoryStream, no need to do async reads.
                        var copyRead = oldBuffer.Read(rentedBuffer);
                        while (copyRead > 0)
                        {
                            await _buffer.WriteAsync(rentedBuffer.AsMemory(0, copyRead), cancellationToken);

                            copyRead = oldBuffer.Read(rentedBuffer);
                        }
                    }
                    finally
                    {
                        _bytePool.Return(rentedBuffer);
                    }
                }
                else
                {
                    await _buffer.WriteAsync(_rentedBuffer.AsMemory(0, (int)oldBuffer.Length), cancellationToken);

                    _bytePool.Return(_rentedBuffer);
                    _rentedBuffer = null;
                }
            }

            if (read > 0)
            {
                await _buffer.WriteAsync(buffer.Slice(0, read), cancellationToken);
            }
            else
            {
                _completelyBuffered = true;
            }

            return(read);
        }
Ejemplo n.º 45
0
        public override unsafe void Write(Slice changeVector, Stream stream, byte[] tempBuffer, OutgoingReplicationStatsScope stats)
        {
            fixed(byte *pTemp = tempBuffer)
            {
                if (AssertChangeVectorSize() > tempBuffer.Length)
                {
                    ThrowTooManyChangeVectorEntries(this, Id);
                }

                var tempBufferPos = WriteCommon(changeVector, pTemp);

                *(long *)(pTemp + tempBufferPos) = LastModifiedTicks;
                tempBufferPos += sizeof(long);

                *(DocumentFlags *)(pTemp + tempBufferPos) = Flags;
                tempBufferPos += sizeof(DocumentFlags);

                *(int *)(pTemp + tempBufferPos) = Id.Size;
                tempBufferPos += sizeof(int);

                Memory.Copy(pTemp + tempBufferPos, Id.Buffer, Id.Size);
                tempBufferPos += Id.Size;

                if (Data != null)
                {
                    *(int *)(pTemp + tempBufferPos) = Data.Size;
                    tempBufferPos += sizeof(int);

                    var docReadPos = 0;
                    while (docReadPos < Data.Size)
                    {
                        var sizeToCopy = Math.Min(Data.Size - docReadPos, tempBuffer.Length - tempBufferPos);
                        if (sizeToCopy == 0) // buffer is full, need to flush it
                        {
                            stream.Write(tempBuffer, 0, tempBufferPos);
                            tempBufferPos = 0;
                            continue;
                        }
                        Memory.Copy(pTemp + tempBufferPos, Data.BasePointer + docReadPos, sizeToCopy);
                        tempBufferPos += sizeToCopy;
                        docReadPos    += sizeToCopy;
                    }

                    stats.RecordDocumentOutput(Data.Size);
                }
                else
                {
                    int dataSize;
                    if (Type == ReplicationItemType.DocumentTombstone)
                    {
                        dataSize = -1;
                    }
                    else if ((Flags & DocumentFlags.DeleteRevision) == DocumentFlags.DeleteRevision)
                    {
                        dataSize = -2;
                    }
                    else
                    {
                        throw new InvalidDataException("Cannot write document with empty data.");
                    }
                    *(int *)(pTemp + tempBufferPos) = dataSize;
                    tempBufferPos += sizeof(int);

                    if (Collection == null) //precaution
                    {
                        throw new InvalidDataException("Cannot write item with empty collection name...");
                    }

                    *(int *)(pTemp + tempBufferPos) = Collection.Size;
                    tempBufferPos += sizeof(int);
                    Memory.Copy(pTemp + tempBufferPos, Collection.Buffer, Collection.Size);
                    tempBufferPos += Collection.Size;

                    stats.RecordDocumentTombstoneOutput();
                }

                stream.Write(tempBuffer, 0, tempBufferPos);
            }
        }
Ejemplo n.º 46
0
 public static ValueTask <int> ReadAtLeastAsync(Stream stream, Memory <byte> buffer, int minimumBytes, bool throwOnEndOfStream, CancellationToken cancellationToken) =>
 new ValueTask <int>(stream.ReadAtLeast(buffer.Span, minimumBytes, throwOnEndOfStream));
Ejemplo n.º 47
0
 public ReturnBufferStream(Stream stream, Memory <byte> buffer)
 {
     _stream = stream;
     _buffer = buffer;
 }
Ejemplo n.º 48
0
 public static ValueTask <int> ReadAsync(Stream stream, Memory <byte> buffer, CancellationToken cancellationToken) =>
 stream.ReadAsync(buffer, cancellationToken);
Ejemplo n.º 49
0
        private void loadImports()
        {
            UInt32 sectionSize = parser.GetUInt32();
            UInt32 vectorSize  = parser.GetUInt32();

            for (uint import = 0; import < vectorSize; import++)
            {
                var mod = parser.GetName();
                var nm  = parser.GetName();

                var type = parser.GetByte();

                if (!Store.Modules.ContainsKey(mod))
                {
                    throw new Exception("Import module not found: " + mod + "@" + nm);
                }
                else if (!Store.Modules[mod].Exports.ContainsKey(nm))
                {
                    string typeString = "unknown";
                    switch (type)
                    {
                    case 0x00:
                        typeString = "function";
                        break;

                    case 0x01:
                        typeString = "table";
                        break;

                    case 0x02:
                        typeString = "memory";
                        break;

                    case 0x03:
                        typeString = "global";
                        break;

                    default:
                        break;
                    }

                    throw new Exception("Import (" + typeString + ") name not found: " + mod + "@" + nm);
                }
                else
                {
                    switch (type)
                    {
                    case 0x00:     // x:typeidx => func x
                        int funcTypeIdx = (int)parser.GetIndex();
                        if (funcTypeIdx >= types.Count())
                        {
                            throw new Exception("Import function type does not exist: " + mod + "@" + nm + " " +
                                                types[funcTypeIdx]);
                        }
                        else if (!types[funcTypeIdx].SameAs(((Function)Store.Modules[mod].Exports[nm]).Type))
                        {
                            throw new Exception("Import function type mismatch: " + mod + "@" + nm + " - " +
                                                types[funcTypeIdx] + " != " +
                                                ((Function)Store.Modules[mod].Exports[nm]).Type);
                        }
                        else
                        {
                            Functions.Add((Function)Store.Modules[mod].Exports[nm]);
                            functionIndex++;
                        }

                        break;

                    case 0x01:     // tt:tabletype => table tt
                        Table t = parser.GetTableType();
                        if (!t.CompatibleWith((Table)Store.Modules[mod].Exports[nm]))
                        {
                            throw new Exception("Import table type mismatch: " + mod + "@" + nm + " " + t + " != " +
                                                (Table)Store.Modules[mod].Exports[nm]);
                        }

                        Tables.Add((Table)Store.Modules[mod].Exports[nm]);
                        break;

                    case 0x02:     // mt:memtype => mem mt
                        Memory m = parser.GetMemType();
                        if (!m.CompatibleWith((Memory)Store.Modules[mod].Exports[nm]))
                        {
                            throw new Exception("Import memory type mismatch: " + mod + "@" + nm + " " + m +
                                                " != " + (Memory)Store.Modules[mod].Exports[nm]);
                        }

                        Console.WriteLine("Memory import found.");
                        Memory.Add((Memory)Store.Modules[mod].Exports[nm]);
                        break;

                    case 0x03:     // gt:globaltype => global gt
                        byte gType;
                        bool mutable;
                        parser.GetGlobalType(out gType, out mutable);

                        if (((Webassembly.Global)Store.Modules[mod].Exports[nm]).Type != gType)
                        {
                            throw new Exception("Import global type mismatch: " + mod + "@" + nm);
                        }

                        var global = (Webassembly.Global)Store.Modules[mod].Exports[nm];
                        global.SetName(mod + "." + nm);
                        Globals.Add(global);
                        break;

                    default:
                        throw new Exception("Invalid import type: 0x" + type.ToString("X"));
                    }
                }
            }
        }
Ejemplo n.º 50
0
 public TheGame(Memory m)
 {
     M = m;
     Address = m.ReadLong(Offsets.Base + m.AddressOfProcess, 0x8, 0xf8);//0xC40
     Game = this;
 }
Ejemplo n.º 51
0
 public static ArraySegment <byte> GetArray(this Memory <byte> memory)
 {
     return(((ReadOnlyMemory <byte>)memory).GetArray());
 }
Ejemplo n.º 52
0
 public void AddExportMemory(string name, Memory m)
 {
     Exports.Add(name, m);
 }
Ejemplo n.º 53
0
 /// <inheritdoc />
 public async ValueTask <ValueWebSocketReceiveResult> ReceiveAsync(
     Memory <byte> payload, CancellationToken token)
 {
     return(await socket.ReceiveAsync(payload, token));
 }
Ejemplo n.º 54
0
 /// <summary>
 /// Returns the text field for cheats, useful if you want to implement custom cheats.
 /// </summary>
 /// <returns></returns>
 public static char[] GetCheatField()
 {
     return(Memory.ReadStringASCII((IntPtr)Addrs.GenericAddrs.STATIC_CHEAT_INPUT_FIELD, 32).ToCharArray());
 }
Ejemplo n.º 55
0
 public PacSignature(Memory <byte> signatureData)
 {
     this.signatureData = signatureData;
 }
Ejemplo n.º 56
0
 public static ArraySegment <byte> GetArray(this Memory <byte> buffer)
 {
     return(((ReadOnlyMemory <byte>)buffer).GetArray());
 }
Ejemplo n.º 57
0
            private async ValueTask <int> ReadAsyncCore(Memory <byte> buffer, CancellationToken cancellationToken)
            {
                // Should only be called if ReadChunksFromConnectionBuffer returned 0.

                Debug.Assert(_connection != null);
                Debug.Assert(buffer.Length > 0);

                CancellationTokenRegistration ctr = _connection.RegisterCancellation(cancellationToken);

                try
                {
                    while (true)
                    {
                        if (_connection == null)
                        {
                            // Fully consumed the response in ReadChunksFromConnectionBuffer.
                            return(0);
                        }

                        if (_state == ParsingState.ExpectChunkData &&
                            buffer.Length >= _connection.ReadBufferSize &&
                            _chunkBytesRemaining >= (ulong)_connection.ReadBufferSize)
                        {
                            // As an optimization, we skip going through the connection's read buffer if both
                            // the remaining chunk data and the buffer are both at least as large
                            // as the connection buffer.  That avoids an unnecessary copy while still reading
                            // the maximum amount we'd otherwise read at a time.
                            Debug.Assert(_connection.RemainingBuffer.Length == 0);
                            int bytesRead = await _connection.ReadAsync(buffer.Slice(0, (int)Math.Min((ulong)buffer.Length, _chunkBytesRemaining))).ConfigureAwait(false);

                            if (bytesRead == 0)
                            {
                                throw new IOException(SR.Format(SR.net_http_invalid_response_premature_eof_bytecount, _chunkBytesRemaining));
                            }
                            _chunkBytesRemaining -= (ulong)bytesRead;
                            if (_chunkBytesRemaining == 0)
                            {
                                _state = ParsingState.ExpectChunkTerminator;
                            }
                            return(bytesRead);
                        }

                        // We're only here if we need more data to make forward progress.
                        await _connection.FillAsync().ConfigureAwait(false);

                        // Now that we have more, see if we can get any response data, and if
                        // we can we're done.
                        int bytesCopied = ReadChunksFromConnectionBuffer(buffer.Span, ctr);
                        if (bytesCopied > 0)
                        {
                            return(bytesCopied);
                        }
                    }
                }
                catch (Exception exc) when(CancellationHelper.ShouldWrapInOperationCanceledException(exc, cancellationToken))
                {
                    throw CancellationHelper.CreateOperationCanceledException(exc, cancellationToken);
                }
                finally
                {
                    ctr.Dispose();
                }
            }
Ejemplo n.º 58
0
 protected override bool EvaluateNode(PerceivedEvent perceivedEvent, Memory memory, CharacterTraits traits)
 {
     return(((Action)perceivedEvent).Message.ToLower().StartsWith("why") ||
            ((Action)perceivedEvent).Message.ToLower().StartsWith("do you know why"));
 }
 internal DefaultAsyncBinaryWriter(Stream stream, Memory <byte> buffer)
 => writer = IAsyncBinaryWriter.Create(stream, buffer);
Ejemplo n.º 60
0
        static void Main(string[] args)
        {
            Console.WriteLine("Initializing Home IO...");
            MemoryBit[]      bitI, bitO, bitIO;
            MemoryByte[]     byteI, byteO, byteIO;
            MemoryShort[]    shortI, shortO, shortIO;
            MemoryInt[]      intI, intO, intIO;
            MemoryLong[]     longI, longO, longIO;
            MemoryFloat[]    floatI, floatO, floatIO;
            MemoryDouble[]   doubleI, doubleO, doubleIO;
            MemoryString[]   stringI, stringO, stringIO;
            MemoryDateTime[] dtI, dtO, dtIO;
            MemoryTimeSpan[] tsI, tsO, tsIO;

            MemoryMap homeio = MemoryMap.Instance;

            bitI  = homeio.GetBitMemories(MemoryType.Input);
            bitO  = homeio.GetBitMemories(MemoryType.Output);
            bitIO = homeio.GetBitMemories(MemoryType.Memory);

            byteI  = homeio.GetByteMemories(MemoryType.Input);
            byteO  = homeio.GetByteMemories(MemoryType.Output);
            byteIO = homeio.GetByteMemories(MemoryType.Memory);

            shortI  = homeio.GetShortMemories(MemoryType.Input);
            shortO  = homeio.GetShortMemories(MemoryType.Output);
            shortIO = homeio.GetShortMemories(MemoryType.Memory);

            intI  = homeio.GetIntMemories(MemoryType.Input);
            intO  = homeio.GetIntMemories(MemoryType.Output);
            intIO = homeio.GetIntMemories(MemoryType.Memory);

            longI  = homeio.GetLongMemories(MemoryType.Input);
            longO  = homeio.GetLongMemories(MemoryType.Output);
            longIO = homeio.GetLongMemories(MemoryType.Memory);

            floatI  = homeio.GetFloatMemories(MemoryType.Input);
            floatO  = homeio.GetFloatMemories(MemoryType.Output);
            floatIO = homeio.GetFloatMemories(MemoryType.Memory);

            doubleI  = homeio.GetDoubleMemories(MemoryType.Input);
            doubleO  = homeio.GetDoubleMemories(MemoryType.Output);
            doubleIO = homeio.GetDoubleMemories(MemoryType.Memory);

            stringI  = homeio.GetStringMemories(MemoryType.Input);
            stringO  = homeio.GetStringMemories(MemoryType.Output);
            stringIO = homeio.GetStringMemories(MemoryType.Memory);

            dtI  = homeio.GetDateTimeMemories(MemoryType.Input);
            dtO  = homeio.GetDateTimeMemories(MemoryType.Output);
            dtIO = homeio.GetDateTimeMemories(MemoryType.Memory);

            tsI  = homeio.GetTimeSpanMemories(MemoryType.Input);
            tsO  = homeio.GetTimeSpanMemories(MemoryType.Output);
            tsIO = homeio.GetTimeSpanMemories(MemoryType.Memory);

            homeio.Update();

            List <string> topics    = new List <string>();
            List <byte>   qosLevels = new List <byte>();

            topicToMemory = new Dictionary <string, Memory>();
            memoryToTopic = new Dictionary <Memory, string>();

            Regex pattern = new Regex(@"[A-Z]\ -\ *");

            Memory[][] allMemories = new Memory[][] {
                bitI, byteI, shortI, intI, longI, floatI, doubleI, stringI, dtI, tsI,
                bitO, byteO, shortO, intO, longO, floatO, doubleO, stringO, dtO, tsO,
                bitIO, byteIO, shortIO, intIO, longIO, floatIO, doubleIO, stringIO, dtIO, tsIO
            };
            foreach (var memoryArray in allMemories)
            {
                foreach (var memory in memoryArray)
                {
                    if (memory.HasName)
                    {
                        string room  = "general";
                        string topic = memory.Name;
                        if (pattern.Match(topic).Success)
                        {
                            room  = topic.Substring(0, 1);
                            topic = topic.Substring(4);
                        }
                        topicToMemory.Add("/home/" + room + "/" + memory.MemoryType + "/" + GetTypeForMemory(memory) + "/" + Clean(topic), memory);
                        memoryToTopic.Add(memory, "/home/" + room + "/" + memory.MemoryType + "/" + GetTypeForMemory(memory) + "/" + Clean(topic));

                        Console.WriteLine(memory.MemoryType + "," + memory.Address + "," + memory.Name + "," + room + "," + GetTypeForMemory(memory) + "," + "/home/" + room + "/" + memory.MemoryType + "/" + GetTypeForMemory(memory) + "/" + Clean(topic));

                        // Listen to memory changes
                        if (memory.MemoryType == MemoryType.Input || memory.MemoryType == MemoryType.Memory)
                        {
                            memory.PropertyChanged += Memory_PropertyChanged;
                        }

                        // Subscribe to the topic
                        if (memory.MemoryType == MemoryType.Output)
                        {
                            topics.Add("/home/" + room + "/" + memory.MemoryType + "/" + GetTypeForMemory(memory) + "/" + Clean(topic));
                            qosLevels.Add(MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE);
                        }
                    }
                }
            }

            if (topics.Count != qosLevels.Count || topics.Count == 0 || qosLevels.Count == 0)
            {
                Console.WriteLine("Home IO init FAILED\n\nMake sure Home IO is running\n");
                Console.WriteLine("Press any key to exit");
                Console.ReadLine();
                return;
            }


            // parametrized
            foreach (string param in args)
            {
                try {
                    MqttClient client = new MqttClient(param);
                    client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
                    client.Connect(Guid.NewGuid().ToString());
                    client.Subscribe(topics.ToArray(), qosLevels.ToArray());
                    clients.Add(client);
                    Console.WriteLine("\nConnected to broker at " + param + "\n");
                } catch (Exception e) {
                    Console.WriteLine("Unable to connect to broker " + param + "\n->" + e);
                }
            }
            // default
            if (args.Length == 0)
            {
                try {
                    MqttClient client = new MqttClient("localhost");
                    client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
                    client.Connect(Guid.NewGuid().ToString());
                    client.Subscribe(topics.ToArray(), qosLevels.ToArray());
                    clients.Add(client);
                    Console.WriteLine("\nConnected to broker at localhost\n");
                } catch (Exception e) {
                    Console.WriteLine("Unable to connect to broker localhost\n->" + e);
                }
            }

            Thread t = new Thread(new ParameterizedThreadStart(HomeIOUpdate));

            t.Start(homeio);

            Console.WriteLine("\nConnected\n\nRunning...");
            Console.WriteLine("Press any key to exit");
            Console.ReadLine();

            t.Abort();
            foreach (MqttClient client in clients)
            {
                client.Disconnect();
            }
            homeio.Dispose();
        }