Ejemplo n.º 1
0
        public unsafe void QueueEvent(IntPtr ptr)
        {
            var eventPtr         = (InputEvent *)ptr;
            var eventSize        = eventPtr->sizeInBytes;
            var alignedEventSize = NumberHelpers.AlignToMultiple(eventSize, 4);

            lock (m_Lock)
            {
                eventPtr->eventId = m_NextEventId;
                ++m_NextEventId;

                // Enlarge buffer, if we have to.
                if ((m_EventWritePosition + alignedEventSize) > m_EventBuffer.Length)
                {
                    var newBufferSize = m_EventBuffer.Length + Mathf.Max((int)alignedEventSize, 1024);
                    var newBuffer     = new NativeArray <byte>(newBufferSize, Allocator.Persistent);
                    UnsafeUtility.MemCpy(newBuffer.GetUnsafePtr(), m_EventBuffer.GetUnsafePtr(), m_EventWritePosition);
                    m_EventBuffer.Dispose();
                    m_EventBuffer = newBuffer;
                }

                // Copy event.
                UnsafeUtility.MemCpy((byte *)m_EventBuffer.GetUnsafePtr() + m_EventWritePosition, ptr.ToPointer(), eventSize);
                m_EventWritePosition += (int)alignedEventSize;
                ++m_EventCount;
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Advance the read position to the next event in the buffer, preserving or not preserving the
        /// current event depending on <paramref name="leaveEventInBuffer"/>.
        /// </summary>
        /// <param name="currentReadPos"></param>
        /// <param name="currentWritePos"></param>
        /// <param name="numEventsRetainedInBuffer"></param>
        /// <param name="numRemainingEvents"></param>
        /// <param name="leaveEventInBuffer"></param>
        /// <remarks>
        /// This method MUST ONLY BE CALLED if the current event has been fully processed. If the at <paramref name="currentWritePos"/>
        /// is smaller than the current event, then this method will OVERWRITE parts or all of the current event.
        /// </remarks>
        internal void AdvanceToNextEvent(ref InputEvent *currentReadPos,
                                         ref InputEvent *currentWritePos, ref int numEventsRetainedInBuffer,
                                         ref int numRemainingEvents, bool leaveEventInBuffer)
        {
            Debug.Assert(Contains(currentReadPos));
            Debug.Assert(Contains(currentWritePos));
            Debug.Assert(currentReadPos >= currentWritePos);

            // Get new read position *before* potentially moving the current event so that we don't
            // end up overwriting the data we need to find the next event in memory.
            var newReadPos = currentReadPos;

            if (numRemainingEvents > 1)
            {
                newReadPos = InputEvent.GetNextInMemoryChecked(currentReadPos, ref this);
            }

            // If the current event should be left in the buffer, advance write position.
            if (leaveEventInBuffer)
            {
                // Move down in buffer if read and write pos have deviated from each other.
                var numBytes = currentReadPos->sizeInBytes;
                if (currentReadPos != currentWritePos)
                {
                    UnsafeUtility.MemMove(currentWritePos, currentReadPos, numBytes);
                }
                currentWritePos = (InputEvent *)((byte *)currentWritePos + NumberHelpers.AlignToMultiple(numBytes, 4));
                ++numEventsRetainedInBuffer;
            }

            currentReadPos = newReadPos;
            --numRemainingEvents;
        }
        public void GetSumOfDigitsTest2()
        {
            var number = "1234";
            var sum    = NumberHelpers.GetSumOfDigits(number);

            Assert.AreEqual(10, sum);
        }
Ejemplo n.º 4
0
        public void InvalidUpdateSystemField(FieldType fieldType, string fieldName, CreateUpdateTestData.InvalidProperty invalidValue)
        {
            var fieldHandler  = new FieldManager();
            var fieldResponse = fieldHandler.GetFieldDetails(fieldName);

            PrAssume.That(fieldResponse, PrIs.SuccessfulResponse(), $"Cannot read field {fieldName}");
            var properties    = new Dictionary <string, object>();
            var deletedField  = UuidUtil.GetId(PreparedDeletedFieldId.Data[CommonHelpers.Resources.FirstOrDefault()]);
            var deletedOption = PreparedDeletedOptionId.Data;

            CreateUpdateTestData.InvalidPropertyValueMapper[invalidValue](properties, deletedField, deletedOption);
            var updateParam = new Dictionary <string, object>
            {
                [Properties.Parameters.Resource.GetEnumStringValue()]   = fieldName.Split('.')[0].ToLower(),
                [Properties.Parameters.Properties.GetEnumStringValue()] = properties
            };
            var request  = NumberHelpers.GenerateRequestUpdate(fieldResponse.Result.Values.Keys.First().ToString(), updateParam);
            var handler  = new DefaultManager();
            var response = handler.Send <object>(FieldManager.FieldHandlingRelativeUrl, request.ToJson(), HttpMethod.PUT);

            if (fieldType == FieldType.Telephone && invalidValue == CreateUpdateTestData.InvalidProperty.TelWithString)
            {
                PrAssert.That(response, PrIs.SuccessfulResponse().And.HttpCode(System.Net.HttpStatusCode.NoContent), "Not able update Field");
            }
            else
            if (fieldType == FieldType.Mail && (invalidValue == CreateUpdateTestData.InvalidProperty.MailWithout || invalidValue == CreateUpdateTestData.InvalidProperty.MailWithoutDomain || invalidValue == CreateUpdateTestData.InvalidProperty.MailWithoutDot || invalidValue == CreateUpdateTestData.InvalidProperty.MailWithoutName || invalidValue == CreateUpdateTestData.InvalidProperty.LeadingDot))
            {
                PrAssert.That(response, PrIs.SuccessfulResponse().And.HttpCode(System.Net.HttpStatusCode.NoContent), "Not able update Field");
            }
            else
            {
                PrAssert.That(response, PrIs.ErrorResponse().And.HttpCode(System.Net.HttpStatusCode.BadRequest), "Still able update Field");
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Get the next event after the given one.
        /// </summary>
        /// <param name="currentPtr">A valid event pointer.</param>
        /// <returns>Pointer to the next event in memory.</returns>
        /// <remarks>
        /// This method applies no checks and must only be called if there is an event following the
        /// given one. Also, the size of the given event must be 100% as the method will simply
        /// take the size and advance the given pointer by it (and aligning it to <see cref="kAlignment"/>).
        /// </remarks>
        /// <seealso cref="GetNextInMemoryChecked"/>
        internal static unsafe InputEvent *GetNextInMemory(InputEvent *currentPtr)
        {
            Debug.Assert(currentPtr != null);
            var alignedSizeInBytes = NumberHelpers.AlignToMultiple(currentPtr->sizeInBytes, kAlignment);

            return((InputEvent *)((byte *)currentPtr + alignedSizeInBytes));
        }
Ejemplo n.º 6
0
        public void InvalidInjectionCreateFieldSpecial(Enum param, Enums.InvalidInjection invalidInjection)
        {
            string parameter  = param.GetEnumStringValue();
            var    properties = NumberHelpers.GenerateRequiredProperties((int)FieldType.Number, Properties.Label.Max);

            if (param.GetType() == typeof(Properties.PropertyName))
            {
                properties[parameter] = MapperData.InvalidInjectionMapper[invalidInjection];
            }
            var handler     = new DefaultManager();
            var createParam = GenerateCreateParam(properties);

            createParam.Remove(Properties.Parameters.Alias.GetEnumStringValue());
            if (param.GetEnumStringValue() != Properties.Parameters.Create.GetEnumStringValue() && param.GetType() == typeof(Properties.Parameters))
            {
                createParam[parameter] = MapperData.InvalidInjectionMapper[invalidInjection];
            }
            var request = GenerateCreateRequest(createParam);

            if (param.GetEnumStringValue() == Properties.Parameters.Create.GetEnumStringValue())
            {
                request[parameter] = MapperData.InvalidInjectionMapper[invalidInjection];
            }
            var response = handler.Send <FieldCreateResponse>(FieldManager.FieldHandlingRelativeUrl, request.ToJson(), HttpMethod.POST);

            PrAssert.That(response, PrIs.ErrorResponse().And.HttpCode(System.Net.HttpStatusCode.BadRequest), "Still able Create Field");
        }
        public MiningResult AttemptMineNewCoin()
        {
            int candidate = NumberHelpers.GenerateRandomNumber(0, 1000);

            bool success = _mathService.IsPrime(candidate);

            if (!success)
            {
                return(new MiningResult()
                {
                    CoinCreated = false
                });
            }
            else
            {
                var newCoin = new Coin()
                {
                    CreationDate = DateTime.Now, Id = Guid.NewGuid()
                };
                return(new MiningResult()
                {
                    CoinCreated = true, NewCoin = newCoin
                });
            }
        }
Ejemplo n.º 8
0
        public void InvalidCreateFieldSpecial(Enum param, MapperData.Invalid invalidValue)
        {
            string parameter  = param.GetEnumStringValue();
            var    properties = NumberHelpers.GenerateRequiredProperties((int)FieldType.Number, Properties.Label.Max);

            if (param.GetType() == typeof(Properties.PropertyName))
            {
                CreateUpdateTestData.InvalidMapperValue[invalidValue](properties, parameter);
            }
            var handler     = new DefaultManager();
            var createParam = GenerateCreateParam(properties);

            CommonMapperValue.AliasMapperValue[Properties.Alias.Max](createParam);
            CreateUpdateTestData.InjectInvalidValue(parameter, createParam, invalidValue);
            var request = GenerateCreateRequest(createParam);

            CreateUpdateTestData.InjectInvalidValue(parameter, request, invalidValue);
            var response = handler.Send <FieldCreateResponse>(FieldManager.FieldHandlingRelativeUrl, request.ToJson(), HttpMethod.POST);

            if (param.GetEnumStringValue() == Properties.PropertyName.Label.GetEnumStringValue() && invalidValue == MapperData.Invalid.SpecialChars)
            {
                PrAssert.That(response, PrIs.SuccessfulResponse().And.HttpCode(System.Net.HttpStatusCode.OK), "Not able Create Field");
            }
            else if ((param.GetEnumStringValue() == Properties.PropertyName.Caption.GetEnumStringValue() && (invalidValue == MapperData.Invalid.StringEmpty || invalidValue == MapperData.Invalid.Missing || invalidValue == MapperData.Invalid.SpecialChars)) ||
                     (param.GetEnumStringValue().ContainsStrings(new[] { Properties.PropertyName.Caption, Properties.PropertyName.Search, Properties.PropertyName.Match, Properties.PropertyName.Web, Properties.PropertyName.Highlight, Properties.PropertyName.Require }.Select(e => e.GetEnumStringValue()).ToArray()) && (invalidValue == MapperData.Invalid.Missing)) ||
                     (param.GetEnumStringValue() == Properties.PropertyName.SType.GetEnumStringValue() && invalidValue == MapperData.Invalid.PositiveNumberWithPlusSign) ||
                     (param.GetEnumStringValue() == Properties.PropertyName.Default.GetEnumStringValue() && invalidValue == MapperData.Invalid.StringEmpty))
            {
                PrAssert.That(response, PrIs.SuccessfulResponse().And.HttpCode(System.Net.HttpStatusCode.OK), "Not able Create Field");
            }
            else
            {
                PrAssert.That(response, PrIs.ErrorResponse().And.HttpCode(System.Net.HttpStatusCode.BadRequest), "Still able Create Field");
            }
        }
Ejemplo n.º 9
0
        public void ValidCreateFieldOptionalProperties(ResourceId resourceId, Properties.Alias alias, Properties.Caption caption, Properties.Search search, Properties.Match match, Properties.Web web, Properties.Highlight highlight, Properties.Require require, Properties.Default defaultProperty, Properties.Min min, Properties.Max max, Properties.Scale scale)
        {
            var handler     = new DefaultManager();
            var properties  = NumberHelpers.GenerateProperties(NumberFieldTestData.NumberFieldType, Properties.Label.Max, caption, search, match, highlight, require, defaultProperty, min, max, scale);
            var createParam = new Dictionary <string, object>
            {
                [Properties.Parameters.Resource.GetEnumStringValue()]   = resourceId.ToString().ToLower(),
                [Properties.Parameters.Alias.GetEnumStringValue()]      = "",
                [Properties.Parameters.Properties.GetEnumStringValue()] = properties
            };

            CommonMapperValue.AliasMapperValue[alias](createParam);
            var request = new Dictionary <string, object>
            {
                [Properties.Parameters.Create.GetEnumStringValue()] = createParam
            }.ToJson();

            PrAssert.That(request, PrIs.Not.EqualTo(string.Empty));
            var response = handler.Send <FieldCreateResponse>(FieldManager.FieldHandlingRelativeUrl, request, HttpMethod.POST);

            PrAssert.That(response, PrIs.SuccessfulResponse().And.HttpCode(System.Net.HttpStatusCode.OK), "Can not Create Field");
            var fieldHandler = new FieldManager();
            var readResponse = fieldHandler.GetFieldDetails(response.Result.Id);

            CommonHelpers.DeleteField(new[] { response.Result.Id });
            PrAssert.That(readResponse, PrIs.SuccessfulResponse().And.HttpCode(System.Net.HttpStatusCode.OK), "Can not Read Field");
            PrAssert.That(readResponse.Result.Values.Count, PrIs.EqualTo(1), "Can not read Field");
            PrAssert.That(readResponse.Result.Values.First().Value.Properties[Properties.PropertyName.SType.GetEnumStringValue()], PrIs.EqualTo($"{NumberFieldTestData.NumberFieldType}"), "Not as expected s.type");
            PrAssert.That(readResponse.Result.Values.First().Value.Properties[Properties.PropertyName.Label.GetEnumStringValue()], PrIs.EqualTo(CommonMapperValue.LabelMapperValue[Properties.Label.Max]), "Not as expected d.label.ja");
            NumberHelpers.VerifyProperties(readResponse.Result.Values.First().Value.Properties, properties);
        }
Ejemplo n.º 10
0
        // Compute the total size of we need for a single state buffer to encompass
        // all devices we have and also linearly assign offsets to all the devices
        // within such a buffer.
        private static uint ComputeSizeOfSingleBufferAndOffsetForEachDevice(InputDevice[] devices, int deviceCount, ref uint[] offsets)
        {
            if (devices == null)
            {
                return(0);
            }

            var result        = new uint[deviceCount];
            var currentOffset = 0u;
            var sizeInBytes   = 0u;

            for (var i = 0; i < deviceCount; ++i)
            {
                var size = devices[i].m_StateBlock.alignedSizeInBytes;
                size = NumberHelpers.AlignToMultiple(size, 4);
                ////REVIEW: what should we do about this case? silently accept it and just give the device the current offset?
                if (size == 0)
                {
                    throw new Exception(string.Format("Device '{0}' has a zero-size state buffer", devices[i]));
                }
                sizeInBytes   += size;
                result[i]      = currentOffset;
                currentOffset += (uint)size;
            }

            offsets = result;
            return(sizeInBytes);
        }
Ejemplo n.º 11
0
        // Compute the total size of we need for a single state buffer to encompass
        // all devices we have and also linearly assign offsets to all the devices
        // within such a buffer.
        private static uint ComputeSizeOfSingleBufferAndOffsetForEachDevice(InputDevice[] devices, int deviceCount, ref uint[] offsets)
        {
            if (devices == null)
            {
                return(0);
            }

            var result      = new uint[deviceCount];
            var sizeInBytes = 0u;

            for (var i = 0; i < deviceCount; ++i)
            {
                var sizeOfDevice = devices[i].m_StateBlock.alignedSizeInBytes;
                sizeOfDevice = NumberHelpers.AlignToMultiple(sizeOfDevice, 4);
                if (sizeOfDevice == 0) // Shouldn't happen as we don't allow empty layouts but make sure we catch this if something slips through.
                {
                    throw new Exception($"Device '{devices[i]}' has a zero-size state buffer");
                }
                result[i]    = sizeInBytes;
                sizeInBytes += sizeOfDevice;
            }

            offsets = result;
            return(sizeInBytes);
        }
Ejemplo n.º 12
0
        static public void Run()
        {
            Link.CreatedEvent += LinkCreated;

            Link x = Net.CreateThing();

            Link number = NumberHelpers.FromNumber(4637694687);


            return;

            do
            {
                Console.Write("-> ");
                string readMessage = Console.ReadLine();

                if (string.Compare("exit", readMessage, ignoreCase: true) == 0)
                {
                    break;
                }

                Console.Write("<- ");
                Console.WriteLine(readMessage);
            }while (true);
        }
Ejemplo n.º 13
0
        public void InvalidUpdateFieldSpecial(Enum param, MapperData.Invalid invalidValue)
        {
            string fieldUUID  = PreparedFieldId.Data[ResourceId.Client].ToString();
            string parameter  = param.GetEnumStringValue() == Properties.Parameters.Guid.GetEnumStringValue() ? fieldUUID : param.GetEnumStringValue();
            var    handler    = new DefaultManager();
            var    properties = NumberHelpers.GenerateRequiredProperties((int)FieldType.Number, Properties.Label.Min);

            if (param.GetType() == typeof(Properties.PropertyName))
            {
                CreateUpdateTestData.InvalidMapperValue[invalidValue](properties, parameter);
            }
            var updateParam = NumberHelpers.GenerateUpdateParam(ResourceId.Client, properties);

            CreateUpdateTestData.InjectInvalidValue(parameter, updateParam, invalidValue);
            var idParam = new Dictionary <string, object>
            {
                [fieldUUID] = updateParam
            };

            CreateUpdateTestData.InjectInvalidValue(parameter, idParam, invalidValue);
            var request = new Dictionary <string, object>
            {
                [Properties.Parameters.Update.GetEnumStringValue()] = idParam
            };

            CreateUpdateTestData.InjectInvalidValue(parameter, request, invalidValue);
            var response = handler.Send <object>(FieldManager.FieldHandlingRelativeUrl, request.ToJson(), HttpMethod.PUT);

            PrAssert.That(response, PrIs.ErrorResponse().And.HttpCode(System.Net.HttpStatusCode.BadRequest), "Still able update Field");
        }
        public void SumOfDigits()
        {
            var number = BigInteger.Pow(2, 1000).ToString();
            var sum    = NumberHelpers.GetSumOfDigits(number);

            Assert.AreEqual(1366, sum);
        }
        // Allocates all buffers to serve the given updates and comes up with a spot
        // for the state block of each device. Returns the new state blocks for the
        // devices (it will *NOT* install them on the devices).
        public unsafe uint[] AllocateAll(InputUpdateType updateMask, InputDevice[] devices)
        {
            uint[] newDeviceOffsets = null;
            sizePerBuffer = ComputeSizeOfSingleBufferAndOffsetForEachDevice(devices, ref newDeviceOffsets);
            if (sizePerBuffer == 0)
            {
                return(null);
            }
            sizePerBuffer = NumberHelpers.AlignToMultiple(sizePerBuffer, 4);

            var isDynamicUpdateEnabled = (updateMask & InputUpdateType.Dynamic) == InputUpdateType.Dynamic;
            var isFixedUpdateEnabled   = (updateMask & InputUpdateType.Fixed) == InputUpdateType.Fixed;

            // Determine how much memory we need.
            var deviceCount = devices.Length;
            var mappingTableSizePerBuffer = (uint)(deviceCount * sizeof(void *) * 2);

            if (isDynamicUpdateEnabled)
            {
                totalSize += sizePerBuffer * 2;
                totalSize += mappingTableSizePerBuffer;
            }
            if (isFixedUpdateEnabled)
            {
                totalSize += sizePerBuffer * 2;
                totalSize += mappingTableSizePerBuffer;
            }
            // Before render doesn't have its own buffers.

#if UNITY_EDITOR
            totalSize += sizePerBuffer * 2;
            totalSize += mappingTableSizePerBuffer;
#endif

            // Allocate.
            m_AllBuffers = (IntPtr)UnsafeUtility.Malloc(totalSize, 4, Allocator.Persistent);
            UnsafeUtility.MemClear(m_AllBuffers.ToPointer(), totalSize);

            // Set up device to buffer mappings.
            var ptr = m_AllBuffers;
            if (isDynamicUpdateEnabled)
            {
                m_DynamicUpdateBuffers =
                    SetUpDeviceToBufferMappings(devices, ref ptr, sizePerBuffer, mappingTableSizePerBuffer);
            }
            if (isFixedUpdateEnabled)
            {
                m_FixedUpdateBuffers =
                    SetUpDeviceToBufferMappings(devices, ref ptr, sizePerBuffer, mappingTableSizePerBuffer);
            }

#if UNITY_EDITOR
            m_EditorUpdateBuffers =
                SetUpDeviceToBufferMappings(devices, ref ptr, sizePerBuffer, mappingTableSizePerBuffer);
#endif

            return(newDeviceOffsets);
        }
        public void MainTest()
        {
            BigInteger a = 1;

            for (var i = 2; i <= 100; i++)
            {
                a = BigInteger.Multiply(a, i);
            }
            Assert.AreEqual(648, NumberHelpers.GetSumOfDigits(a.ToString()));
        }
Ejemplo n.º 17
0
        public void InvalidSpecialCreateFieldSpecial(ResourceId resourceId)
        {
            var properties  = NumberHelpers.GenerateRequiredProperties((int)FieldType.Number, Properties.Label.Max);
            var handler     = new DefaultManager();
            var createParam = GenerateCreateParam(properties);
            var request     = GenerateCreateRequest(createParam);
            var response    = handler.Send <FieldCreateResponse>(FieldManager.FieldHandlingRelativeUrl, request.ToJson(), HttpMethod.POST);

            PrAssert.That(response, PrIs.ErrorResponse().And.HttpCode(System.Net.HttpStatusCode.BadRequest), "Still able Create Field");
        }
Ejemplo n.º 18
0
        public void InvalidCreateFieldSpecial(ResourceId resource, NumberHelpers.InvalidCreateField invalidCreateField)
        {
            var handler    = new FieldManager();
            var properties = NumberHelpers.GenerateRequiredProperties(NumberFieldTestData.NumberFieldType, Properties.Label.Max);

            NumberHelpers.InvalidCreateMapperValue[invalidCreateField](properties);
            var response = handler.CreateField(resource, properties);

            PrAssert.That(response, PrIs.ErrorResponse().And.HttpCode(System.Net.HttpStatusCode.BadRequest), "Still able Create Field");
        }
    public void Utilities_NumberHelpers_CanConvertUIntToNormalizedFloatAndBack(uint value, uint minValue, uint maxValue, float expected)
    {
        var result = NumberHelpers.UIntToNormalizedFloat(value, minValue, maxValue);

        Assert.That(result, Is.EqualTo(expected).Within(float.Epsilon));

        var integer = NumberHelpers.NormalizedFloatToUInt(result, minValue, maxValue);

        Assert.That(integer, Is.EqualTo(Clamp(value, minValue, maxValue)));
    }
Ejemplo n.º 20
0
        public InputEvent *AllocateEvent(int sizeInBytes, int capacityIncrementInBytes = 2048)
        {
            if (sizeInBytes < InputEvent.kBaseEventSize)
            {
                throw new ArgumentException(
                          string.Format("sizeInBytes must be >= sizeof(InputEvent) == {0} (was {1})",
                                        InputEvent.kBaseEventSize, sizeInBytes),
                          "sizeInBytes");
            }

            var alignedSizeInBytes = NumberHelpers.AlignToMultiple(sizeInBytes, InputEvent.kAlignment);

            // See if we need to enlarge our buffer.
            var currentCapacity = capacityInBytes;

            if (currentCapacity < alignedSizeInBytes)
            {
                // Yes, so reallocate.
                var newCapacity = Math.Max(currentCapacity + capacityIncrementInBytes,
                                           currentCapacity + alignedSizeInBytes);
                var newSize = this.sizeInBytes + newCapacity;
                if (newSize > int.MaxValue)
                {
                    throw new NotImplementedException("NativeArray long support");
                }
                var newBuffer =
                    new NativeArray <byte>((int)newSize, Allocator.Persistent, NativeArrayOptions.ClearMemory);

                if (m_Buffer.IsCreated)
                {
                    UnsafeUtility.MemCpy(newBuffer.GetUnsafePtr(), m_Buffer.GetUnsafeReadOnlyPtr(), this.sizeInBytes);
                }
                else
                {
                    m_BufferEnd = 0;
                }

                if (m_WeOwnTheBuffer)
                {
                    m_Buffer.Dispose();
                }
                m_Buffer         = newBuffer;
                m_WeOwnTheBuffer = true;
            }

            var eventPtr = (InputEvent *)((byte *)m_Buffer.GetUnsafePtr() + m_BufferEnd);

            eventPtr->sizeInBytes = (uint)sizeInBytes;
            m_BufferEnd          += alignedSizeInBytes;
            ++m_EventCount;

            return(eventPtr);
        }
Ejemplo n.º 21
0
    public unsafe void State_CanGetMetrics()
    {
        // Make sure we start out with blank data.
        var metrics = InputSystem.GetMetrics();

        Assert.That(metrics.totalEventCount, Is.Zero);
        Assert.That(metrics.totalEventBytes, Is.Zero);
        Assert.That(metrics.totalUpdateCount, Is.Zero);

        var device1 = InputSystem.AddDevice <Gamepad>();
        var device2 = InputSystem.AddDevice <Keyboard>();

        InputSystem.QueueStateEvent(device1, new GamepadState());
        InputSystem.QueueStateEvent(device1, new GamepadState());
        InputSystem.QueueStateEvent(device2, new KeyboardState());
        InputSystem.Update();

        var device3 = InputSystem.AddDevice <Mouse>();

        InputSystem.RemoveDevice(device3);

        metrics = InputSystem.GetMetrics();

        // Manually compute the size of the combined state buffer so that we
        // have a check that catches if the size changes (for good or no good reason).
        var overheadPerBuffer       = 3 * sizeof(void *) * 2; // Mapping table with front and back buffer pointers for three devices.
        var combinedDeviceStateSize = NumberHelpers.AlignToMultiple(
            device1.stateBlock.alignedSizeInBytes + device2.stateBlock.alignedSizeInBytes +
            device3.stateBlock.alignedSizeInBytes, 4);
        var sizePerBuffer      = overheadPerBuffer + combinedDeviceStateSize * 2; // Front+back
        var sizeOfSingleBuffer = combinedDeviceStateSize;

        const int kDoubleBufferCount =
            #if UNITY_EDITOR
            3     // Dynamic + fixed + editor
            #else
            2     // Dynamic + fixed
            #endif
        ;

        var eventByteCount =
            StateEvent.GetEventSizeWithPayload <GamepadState>() * 2 +
            StateEvent.GetEventSizeWithPayload <KeyboardState>();

        Assert.That(metrics.maxNumDevices, Is.EqualTo(3));
        Assert.That(metrics.maxStateSizeInBytes, Is.EqualTo((kDoubleBufferCount * sizePerBuffer) + (sizeOfSingleBuffer * 2)));
        Assert.That(metrics.totalEventBytes, Is.EqualTo(eventByteCount));
        Assert.That(metrics.totalEventCount, Is.EqualTo(3));
        Assert.That(metrics.totalUpdateCount, Is.EqualTo(1));
        Assert.That(metrics.totalEventProcessingTime, Is.GreaterThan(0.0000001));
        Assert.That(metrics.averageEventBytesPerFrame, Is.EqualTo(eventByteCount).Within(0.00001));
        Assert.That(metrics.averageProcessingTimePerEvent, Is.GreaterThan(0.0000001));
    }
Ejemplo n.º 22
0
 public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
 {
     if (!string.IsNullOrEmpty(value.ToString()))
     {
         var money = value.ToString().Replace(".", "");
         if (NumberHelpers.IsNumber(money))
         {
             return(Decimal.Parse(money));
         }
     }
     return(DependencyProperty.UnsetValue);
 }
Ejemplo n.º 23
0
        private string getEmotion(EmotionScores emotion)
        {
            KeyValuePair <string, float> bestMatch = new KeyValuePair <string, float>("", 0);

            foreach (KeyValuePair <string, float> item in emotion.ToRankedList())
            {
                if (item.Value > bestMatch.Value)
                {
                    bestMatch = item;
                }
            }
            return(bestMatch.Key + " (" + NumberHelpers.ToPercent(bestMatch.Value) + ")");
        }
Ejemplo n.º 24
0
        public override void Execute(string text)
        {
            base.Execute(text);

            char[] sp   = { ' ', '\t' };
            var    argv = text.Split(sp, 1, StringSplitOptions.RemoveEmptyEntries);

            if (argv.Length != 1)
            {
                Context.CONSOLE.Write(CommandHelp);
                return;
            }

            var strArgAddr = argv[0];

            var varArgAddr = Context.IDE.Debugger.GetExpression(strArgAddr, false, 100);
            var processId  = Context.IDE.Debugger.CurrentProcess.ProcessID;

            if (!varArgAddr.IsValidValue)
            {
                Context.CONSOLE.Write("Argument <address>: " + strArgAddr + " is invalid!");
                return;
            }

            long lpAddress = 0;

            var numStyleAddr = NumberHelpers.IsHexNumber(varArgAddr.Value)
                ? NumberStyles.HexNumber
                : NumberStyles.Integer;
            var bRet = true;

            bRet = bRet && NumberHelpers.TryParseLong(varArgAddr.Value, numStyleAddr, out lpAddress);

            if (!bRet)
            {
                Context.CONSOLE.Write("Failed to evaluate command arguments!");
                return;
            }

            var ntdbgStatus = NativeMethods.NtdbgOk;

            if (NativeMethods.NtdbgOk != (ntdbgStatus = MemoryHelpers.ProcFree(processId, lpAddress)))
            {
                Context.CONSOLE.Write("Failed to release memory!");
                Context.CONSOLE.Write("Error code:" + ntdbgStatus + " - " + NativeMethods.GetStatusString(ntdbgStatus) +
                                      ".");
                return;
            }

            Context.CONSOLE.Write("Released memory at address: " + NumberHelpers.ToHex(lpAddress));
        }
Ejemplo n.º 25
0
        public override void Execute(string text)
        {
            base.Execute(text);

            char[] sp   = { ' ', '\t' };
            var    argv = text.Split(sp, 1, StringSplitOptions.RemoveEmptyEntries);

            if (argv.Length != 1)
            {
                Context.CONSOLE.Write(CommandHelp);
                return;
            }

            var strArgSize = argv[0];

            var varArgSize = Context.IDE.Debugger.GetExpression(strArgSize, false, 100);
            var processId  = Context.IDE.Debugger.CurrentProcess.ProcessID;

            if (!varArgSize.IsValidValue)
            {
                Context.CONSOLE.Write("Argument <size>: " + strArgSize + " is invalid!");
                return;
            }

            long dataSize = 0;

            var numStyleSize = NumberHelpers.IsHexNumber(varArgSize.Value)
                ? NumberStyles.HexNumber
                : NumberStyles.Integer;
            var bRet = true;

            bRet = bRet && NumberHelpers.TryParseLong(varArgSize.Value, numStyleSize, out dataSize);

            if (!bRet)
            {
                Context.CONSOLE.Write("Failed to evaluate command arguments!");
                return;
            }

            ulong qwPtr = 0;

            qwPtr = MemoryHelpers.ProcAlloc(processId, dataSize);

            if (0 == qwPtr)
            {
                Context.CONSOLE.Write("Failed to allocate memory!");
                return;
            }

            Context.CONSOLE.Write("Allocated: " + dataSize + " bytes at address: " + NumberHelpers.ToHex((long)qwPtr));
        }
Ejemplo n.º 26
0
        public void ValidCreateFieldRequiredProperties(ResourceId resourceId, Properties.Label label)
        {
            var handler    = new FieldManager();
            var properties = NumberHelpers.GenerateRequiredProperties(NumberFieldTestData.NumberFieldType, label);
            var response   = handler.CreateField(resourceId, properties);

            PrAssert.That(response, PrIs.SuccessfulResponse().And.HttpCode(System.Net.HttpStatusCode.OK), "Can not Create Field");
            var readResponse = handler.GetFieldDetails(response.Result.Id);

            CommonHelpers.DeleteField(new[] { response.Result.Id });
            PrAssert.That(readResponse, PrIs.SuccessfulResponse().And.HttpCode(System.Net.HttpStatusCode.OK), "Can not Read Field");
            PrAssert.That(readResponse.Result.Values.Count, PrIs.EqualTo(1), "Can not read Field");
            PrAssert.That(readResponse.Result.Values.First().Value.Properties[Properties.PropertyName.SType.GetEnumStringValue()], PrIs.EqualTo($"{NumberFieldTestData.NumberFieldType}"), "Not as expected s.type");
            PrAssert.That(readResponse.Result.Values.First().Value.Properties[Properties.PropertyName.Label.GetEnumStringValue()], PrIs.EqualTo(CommonMapperValue.LabelMapperValue[label]), "Not as expected d.label.ja");
        }
        public void ValidDuplicateCreateField(ResourceId resourceId, System.Enum param, Enums.ValidDuplicated validDuplicated)
        {
            var handler         = new DefaultManager();
            var properties      = NumberHelpers.GenerateProperties(NumberFieldTestData.NumberFieldType, Properties.Label.Max, Properties.Caption.Min, Properties.Search.True, Properties.Match.True, Properties.Highlight.True, Properties.Require.True, Properties.Default.EqualTo, Properties.Min.EqualToMax, Properties.Max.EqualToMin, Properties.Scale.One);
            var otherProperties = NumberHelpers.GenerateProperties(NumberFieldTestData.NumberFieldType, Properties.Label.Min, Properties.Caption.Max, Properties.Search.False, Properties.Match.False, Properties.Highlight.False, Properties.Require.False, Properties.Default.LessThan, Properties.Min.LessThanMax, Properties.Max.GreaterThanMin, Properties.Scale.One);

            if (param.GetEnumStringValue() == Properties.PropertyName.Scale.GetEnumStringValue() && validDuplicated == Enums.ValidDuplicated.NotSameValue)
            {
                NumberHelpers.ScaleMapperValue[Properties.Scale.Two](properties);
            }
            var request  = CommonHelpers.CreateDuplicateRequest(resourceId, properties, otherProperties, param, validDuplicated);
            var response = handler.Send <FieldCreateResponse>(FieldManager.FieldHandlingRelativeUrl, request, HttpMethod.POST);

            PrAssert.That(response, PrIs.SuccessfulResponse().And.HttpCode(System.Net.HttpStatusCode.OK), "Can not Create Field");
            CommonHelpers.DeleteField(new[] { response.Result.Id });
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Get the next event after the given one. Throw if that would point to invalid memory as indicated
        /// by the given memory buffer.
        /// </summary>
        /// <param name="currentPtr">A valid event pointer to an event inside <paramref name="buffer"/>.</param>
        /// <param name="buffer">Event buffer in which to advance to the next event.</param>
        /// <returns>Pointer to the next event.</returns>
        /// <exception cref="InvalidOperationException">There are no more events in the given buffer.</exception>
        internal static unsafe InputEvent *GetNextInMemoryChecked(InputEvent *currentPtr, ref InputEventBuffer buffer)
        {
            Debug.Assert(currentPtr != null);
            Debug.Assert(buffer.Contains(currentPtr), "Given event is not contained in given event buffer");

            var alignedSizeInBytes = NumberHelpers.AlignToMultiple(currentPtr->sizeInBytes, kAlignment);
            var nextPtr            = (InputEvent *)((byte *)currentPtr + alignedSizeInBytes);

            if (!buffer.Contains(nextPtr))
            {
                throw new InvalidOperationException(string.Format(
                                                        "Event '{0}' is last event in given buffer with size {1}", new InputEventPtr(currentPtr),
                                                        buffer.sizeInBytes));
            }

            return(nextPtr);
        }
Ejemplo n.º 29
0
        public void ValidUpdateFieldSpecial(ResourceId resourceId, string field, Selects.ValidSelect validValue)
        {
            var fieldHandler  = new FieldManager();
            var fieldResponse = fieldHandler.GetFieldGuid(new[] { field }, new[] { resourceId });

            PrAssume.That(fieldResponse, PrIs.SuccessfulResponse(), $"Cannot read field {field}");
            string fieldUUID  = fieldResponse.Result.Result.First().Id.ToString();
            var    handler    = new DefaultManager();
            var    properties = new Dictionary <string, object>();

            CreateUpdateTestData.ValidPropertyValueMapper[validValue](properties);
            var updateParam = NumberHelpers.GenerateUpdateParam(resourceId, properties);
            var request     = NumberHelpers.GenerateRequestUpdate(fieldUUID, updateParam);
            var response    = handler.Send <object>(FieldManager.FieldHandlingRelativeUrl, request.ToJson(), HttpMethod.PUT);

            PrAssert.That(response, PrIs.SuccessfulResponse().And.HttpCode(System.Net.HttpStatusCode.NoContent), "Still able update Field");
        }
Ejemplo n.º 30
0
        public void ValidDuplicateUpdateUserField(ResourceId resourceId, System.Enum param, Enums.ValidDuplicated validDuplicated)
        {
            var fieldUUID       = PreparedFieldId.Data[$"{resourceId}0"];
            var otherFieldUUID  = PreparedFieldId.Data[$"{resourceId}1"];
            var handler         = new DefaultManager();
            var properties      = NumberHelpers.GenerateProperties(CurrencyFieldTestData.CurrencyFieldType, Properties.Label.Max, Properties.Caption.Min, Properties.Search.True, Properties.Match.True, Properties.Highlight.True, Properties.Require.True, Properties.Default.EqualTo, Properties.Min.EqualToMax, Properties.Max.EqualToMin, Properties.Scale.One);
            var otherProperties = NumberHelpers.GenerateProperties(CurrencyFieldTestData.CurrencyFieldType, Properties.Label.Min, Properties.Caption.Max, Properties.Search.False, Properties.Match.False, Properties.Highlight.False, Properties.Require.False, Properties.Default.LessThan, Properties.Min.LessThanMax, Properties.Max.GreaterThanMin, Properties.Scale.One);

            if (param.GetEnumStringValue() == Properties.PropertyName.Scale.GetEnumStringValue() && validDuplicated == Enums.ValidDuplicated.NotSameValue)
            {
                NumberHelpers.ScaleMapperValue[Properties.Scale.Two](properties);
            }
            var request  = CommonHelpers.UpdateDuplicateRequest(resourceId, fieldUUID, otherFieldUUID, properties, otherProperties, param, validDuplicated);
            var response = handler.Send <object>(FieldManager.FieldHandlingRelativeUrl, request, HttpMethod.PUT);

            PrAssert.That(response, PrIs.SuccessfulResponse().And.HttpCode(System.Net.HttpStatusCode.NoContent), "Can not update Field");
        }