Пример #1
0
        public static string SnakeCaseToCamelCase(this string snakeCaseName)
        {
            bool next_upper = true;

            ValueStringBuilder sb = new ValueStringBuilder(snakeCaseName.Length);

            for (int i = 0; i < snakeCaseName.Length; i++)
            {
                if (snakeCaseName[i] == '_')
                {
                    next_upper = true;
                }
                else
                {
                    if (next_upper)
                    {
                        sb.Append(char.ToUpperInvariant(snakeCaseName[i]));
                        next_upper = false;
                    }
                    else
                    {
                        sb.Append(snakeCaseName[i]);
                    }
                }
            }

            string s = sb.ToString();

            sb.Dispose();
            return(s);
        }
Пример #2
0
        public static string GetTempFileName()
        {
            Span <char>        initialTempPathBuffer = stackalloc char[PathInternal.MaxShortPath];
            ValueStringBuilder tempPathBuilder       = new ValueStringBuilder(initialTempPathBuffer);

            GetTempPath(ref tempPathBuilder);

            Span <char> initialBuffer = stackalloc char[PathInternal.MaxShortPath];
            var         builder       = new ValueStringBuilder(initialBuffer);

            uint result = Interop.Kernel32.GetTempFileNameW(
                ref tempPathBuilder.GetPinnableReference(), "tmp", 0, ref builder.GetPinnableReference());

            tempPathBuilder.Dispose();

            if (result == 0)
            {
                throw Win32Marshal.GetExceptionForLastWin32Error();
            }

            builder.Length = builder.RawChars.IndexOf('\0');

            string path = PathHelper.Normalize(ref builder);

            builder.Dispose();
            return(path);
        }
Пример #3
0
        public static void HtmlDecode(string?value, TextWriter output)
        {
            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            if (string.IsNullOrEmpty(value))
            {
                output.Write(value);
                return;
            }

            ReadOnlySpan <char> valueSpan = value.AsSpan();

            int index = IndexOfHtmlDecodingChars(valueSpan);

            if (index == -1)
            {
                output.Write(value);
                return;
            }

            // In the worst case the decoded string has the same length.
            // For small inputs we use stack allocation.
            ValueStringBuilder sb = value.Length <= 256 ?
                                    new ValueStringBuilder(stackalloc char[256]) :
                                    new ValueStringBuilder(value.Length);

            sb.Append(valueSpan.Slice(0, index));
            HtmlDecode(valueSpan.Slice(index), ref sb);

            output.Write(sb.AsSpan());
            sb.Dispose();
        }
Пример #4
0
        // Returns a unique temporary file name, and creates a 0-byte file by that
        // name on disk.
        public static string GetTempFileName()
        {
            Span <char>        initialTempPathBuffer = stackalloc char[PathInternal.MaxShortPath];
            ValueStringBuilder tempPathBuilder       = new ValueStringBuilder(initialTempPathBuffer);

            GetTempPath(ref tempPathBuilder);

            Span <char> initialBuffer = stackalloc char[PathInternal.MaxShortPath];
            var         builder       = new ValueStringBuilder(initialBuffer);

            uint result = 0;

            while ((result = Interop.Kernel32.GetTempFileNameW(
                        ref tempPathBuilder.GetPinnableReference(), "tmp", 0, ref builder.GetPinnableReference())) > builder.Capacity)
            {
                // Reported size is greater than the buffer size. Increase the capacity.
                builder.EnsureCapacity(checked ((int)result));
            }

            tempPathBuilder.Dispose();

            if (result == 0)
            {
                throw Win32Marshal.GetExceptionForLastWin32Error();
            }

            builder.Length = (int)result;

            string path = PathHelper.Normalize(ref builder);

            builder.Dispose();
            return(path);
        }
Пример #5
0
        public static string CamelCaseToSnakeCase(this string camelCaseName)
        {
            ValueStringBuilder sb = new ValueStringBuilder(camelCaseName.Length * 2);

            if (char.IsUpper(camelCaseName[0]))
            {
                sb.Append(char.ToLowerInvariant(camelCaseName[0]));
            }

            for (int i = 1; i < camelCaseName.Length; i++)
            {
                if (char.IsUpper(camelCaseName[i]))
                {
                    sb.Append("_");
                    sb.Append(char.ToLowerInvariant(camelCaseName[i]));
                }
                else
                {
                    sb.Append(camelCaseName[i]);
                }
            }

            string s = sb.ToString();

            sb.Dispose();

            return(s);
        }
Пример #6
0
        private string ReadProperties(uint serial, out string htmltext)
        {
            bool hasStartColor = false;

            string result = null;

            htmltext = string.Empty;

            if (SerialHelper.IsValid(serial) && World.OPL.TryGetNameAndData(serial, out string name, out string data))
            {
                ValueStringBuilder sbHTML = new ValueStringBuilder();
                {
                    ValueStringBuilder sb = new ValueStringBuilder();
                    {
                        if (!string.IsNullOrEmpty(name))
                        {
                            if (SerialHelper.IsItem(serial))
                            {
                                sbHTML.Append("<basefont color=\"yellow\">");
                                hasStartColor = true;
                            }
                            else
                            {
                                Mobile mob = World.Mobiles.Get(serial);

                                if (mob != null)
                                {
                                    sbHTML.Append(Notoriety.GetHTMLHue(mob.NotorietyFlag));
                                    hasStartColor = true;
                                }
                            }

                            sb.Append(name);
                            sbHTML.Append(name);

                            if (hasStartColor)
                            {
                                sbHTML.Append("<basefont color=\"#FFFFFFFF\">");
                            }
                        }

                        if (!string.IsNullOrEmpty(data))
                        {
                            sb.Append('\n');
                            sb.Append(data);
                            sbHTML.Append('\n');
                            sbHTML.Append(data);
                        }

                        htmltext = sbHTML.ToString();
                        result   = sb.ToString();

                        sb.Dispose();
                        sbHTML.Dispose();
                    }
                }
            }
            return(string.IsNullOrEmpty(result) ? null : result);
        }
Пример #7
0
        public static string GetTempPath()
        {
            Span <char> initialBuffer = stackalloc char[PathInternal.MaxShortPath];
            var         builder       = new ValueStringBuilder(initialBuffer);

            GetTempPath(ref builder);

            string path = PathHelper.Normalize(ref builder);

            builder.Dispose();
            return(path);
        }
        public void DisposeTest()
        {
            ValueStringBuilder sb = ValueStringBuilder.CreateFrom("Hello World".AsSpan());

            Assert.AreEqual(11, sb.Length);
            Assert.AreEqual("Hello World", sb.ToString());

            sb.Dispose();
            Assert.True(sb.IsEmpty);
            Assert.AreEqual(0, sb.Length);
            Assert.AreEqual(0, sb.Capacity);
        }
        internal static unsafe string RemoveRelativeSegments(string path, int rootLength)
        {
            // ISSUE: untyped stack allocation
            ValueStringBuilder sb = new ValueStringBuilder(new Span <char>((void *)__untypedstackalloc(new IntPtr(520)), 260));

            if (PathInternal.RemoveRelativeSegments(path.AsSpan(), rootLength, ref sb))
            {
                path = sb.ToString();
            }
            sb.Dispose();
            return(path);
        }
Пример #10
0
        /// <summary>
        /// Try to remove relative segments from the given path (without combining with a root).
        /// </summary>
        /// <param name="path">Input path</param>
        /// <param name="rootLength">The length of the root of the given path</param>
        internal static string RemoveRelativeSegments(string path, int rootLength)
        {
            Span <char>        initialBuffer = stackalloc char[260 /* PathInternal.MaxShortPath */];
            ValueStringBuilder sb            = new ValueStringBuilder(initialBuffer);

            if (RemoveRelativeSegments(path.AsSpan(), rootLength, ref sb))
            {
                path = sb.ToString();
            }

            sb.Dispose();
            return(path);
        }
Пример #11
0
        internal static string Normalize(ref ValueStringBuilder path)
        {
            Span <char> initialBuffer = stackalloc char[PathInternal.MaxShortPath];
            var         builder       = new ValueStringBuilder(initialBuffer);

            // Get the full path
            GetFullPathName(path.AsSpan(terminate: true), ref builder);

            string result = builder.AsSpan().IndexOf('~') >= 0
                ? TryExpandShortFileName(ref builder, originalPath: null)
                : builder.ToString();

            // Clear the buffer
            builder.Dispose();
            return(result);
        }
Пример #12
0
        public static string UnescapeDataString(string stringToUnescape)
        {
            if ((object)stringToUnescape == null)
            {
                throw new ArgumentNullException(nameof(stringToUnescape));
            }

            if (stringToUnescape.Length == 0)
            {
                return(string.Empty);
            }

            unsafe
            {
                fixed(char *pStr = stringToUnescape)
                {
                    int position;

                    for (position = 0; position < stringToUnescape.Length; ++position)
                    {
                        if (pStr[position] == '%')
                        {
                            break;
                        }
                    }

                    if (position == stringToUnescape.Length)
                    {
                        return(stringToUnescape);
                    }

                    UnescapeMode unescapeMode = UnescapeMode.Unescape | UnescapeMode.UnescapeAll;

                    position = 0;
                    ValueStringBuilder vsb = new ValueStringBuilder(stringToUnescape.Length);

                    UriHelper.UnescapeString(stringToUnescape, 0, stringToUnescape.Length, ref vsb, ref position,
                                             c_DummyChar, c_DummyChar, c_DummyChar, unescapeMode, null, false);

                    ReadOnlySpan <char> resultSpan = vsb.AsSpan(0, position);
                    string result = resultSpan.SequenceEqual(stringToUnescape) ? stringToUnescape : resultSpan.ToString();

                    vsb.Dispose();
                    return(result);
                }
            }
        }
Пример #13
0
        internal static string Normalize(string path)
        {
            Span <char> initialBuffer = stackalloc char[PathInternal.MaxShortPath];
            var         builder       = new ValueStringBuilder(initialBuffer);

            // Get the full path
            GetFullPathName(path.AsSpan(), ref builder);

            // If we have the exact same string we were passed in, don't allocate another string.
            // TryExpandShortName does this input identity check.
            string result = builder.AsSpan().IndexOf('~') >= 0
                ? TryExpandShortFileName(ref builder, originalPath: path)
                : builder.AsSpan().Equals(path.AsSpan(), StringComparison.Ordinal) ? path : builder.ToString();

            // Clear the buffer
            builder.Dispose();
            return(result);
        }
Пример #14
0
        public override void Update(double totalTime, double frameTime)
        {
            base.Update(totalTime, frameTime);

            if (Time.Ticks > _time_to_update)
            {
                _time_to_update = Time.Ticks + 100;

                if (!NetClient.Socket.IsConnected)
                {
                    _ping = NetClient.LoginSocket.Statistics.Ping;
                    _deltaBytesReceived = NetClient.LoginSocket.Statistics.DeltaBytesReceived;
                    _deltaBytesSent     = NetClient.LoginSocket.Statistics.DeltaBytesSent;
                }
                else if (!NetClient.Socket.IsDisposed)
                {
                    _ping = NetClient.Socket.Statistics.Ping;
                    _deltaBytesReceived = NetClient.Socket.Statistics.DeltaBytesReceived;
                    _deltaBytesSent     = NetClient.Socket.Statistics.DeltaBytesSent;
                }

                Span <char>        span = stackalloc char[128];
                ValueStringBuilder sb   = new ValueStringBuilder(span);

                if (IsMinimized)
                {
                    sb.Append($"Ping: {_ping} ms");
                }
                else
                {
                    sb.Append($"Ping: {_ping} ms\n{"In:"} {NetStatistics.GetSizeAdaptive(_deltaBytesReceived),-6} {"Out:"} {NetStatistics.GetSizeAdaptive(_deltaBytesSent),-6}");
                }

                _cacheText = sb.ToString();

                sb.Dispose();

                Vector2 size = Fonts.Bold.MeasureString(_cacheText);

                _trans.Width   = Width = (int)(size.X + 20);
                _trans.Height  = Height = (int)(size.Y + 20);
                WantUpdateSize = true;
            }
        }
Пример #15
0
        public void Dispose_ClearsBuilder_ThenReusable()
        {
            const string Text1 = "test";
            var          vsb   = new ValueStringBuilder();

            vsb.Append(Text1);
            Assert.Equal(Text1.Length, vsb.Length);

            vsb.Dispose();

            Assert.Equal(0, vsb.Length);
            Assert.Equal(string.Empty, vsb.ToString());
            Assert.True(vsb.TryCopyTo(Span <char> .Empty, out _));

            const string Text2 = "another test";

            vsb.Append(Text2);
            Assert.Equal(Text2.Length, vsb.Length);
            Assert.Equal(Text2, vsb.ToString());
        }
Пример #16
0
        public static void HtmlEncode(string?value, TextWriter output)
        {
            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }
            if (string.IsNullOrEmpty(value))
            {
                output.Write(value);
                return;
            }

            ReadOnlySpan <char> valueSpan = value.AsSpan();

            // Don't create ValueStringBuilder if we don't have anything to encode
            int index = IndexOfHtmlEncodingChars(valueSpan);

            if (index == -1)
            {
                output.Write(value);
                return;
            }

            // For small inputs we allocate on the stack. In most cases a buffer three
            // times larger the original string should be sufficient as usually not all
            // characters need to be encoded.
            // For larger string we rent the input string's length plus a fixed
            // conservative amount of chars from the ArrayPool.
            Span <char> buffer = value.Length < 80 ?
                                 stackalloc char[256] :
                                 null;
            ValueStringBuilder sb = buffer != null ?
                                    new ValueStringBuilder(buffer) :
                                    new ValueStringBuilder(value.Length + 200);

            sb.Append(valueSpan.Slice(0, index));
            HtmlEncode(valueSpan.Slice(index), ref sb);

            output.Write(sb.AsSpan());
            sb.Dispose();
        }
Пример #17
0
        internal static unsafe char[] UnescapeString(char *pStr, int start, int end, char[] dest, ref int destPosition,
                                                     char rsvd1, char rsvd2, char rsvd3, UnescapeMode unescapeMode, UriParser?syntax, bool isQuery)
        {
            ValueStringBuilder vsb = new ValueStringBuilder(dest.Length);

            vsb.Append(dest.AsSpan(0, destPosition));
            UnescapeString(pStr, start, end, ref vsb, rsvd1, rsvd2, rsvd3, unescapeMode,
                           syntax, isQuery);

            if (vsb.Length > dest.Length)
            {
                dest = vsb.AsSpan().ToArray();
            }
            else
            {
                vsb.AsSpan(destPosition).TryCopyTo(dest.AsSpan(destPosition));
            }
            destPosition = vsb.Length;
            vsb.Dispose();
            return(dest);
        }
Пример #18
0
        internal string ReadASCII(int size)
        {
            EnsureSize(size);

            Span <char>        span = stackalloc char[size];
            ValueStringBuilder sb   = new ValueStringBuilder(span);

            for (int i = 0; i < size; i++)
            {
                char c = (char)ReadByte();

                if (c != 0)
                {
                    sb.Append(c);
                }
            }

            string ss = sb.ToString();

            sb.Dispose();

            return(ss);
        }
        public string CreateReagentListString(string separator)
        {
            ValueStringBuilder sb = new ValueStringBuilder();
            {
                for (int i = 0; i < Regs.Length; i++)
                {
                    switch (Regs[i])
                    {
                    // britanian reagents
                    case Reagents.BlackPearl:
                        sb.Append(ResGeneral.BlackPearl);

                        break;

                    case Reagents.Bloodmoss:
                        sb.Append(ResGeneral.Bloodmoss);

                        break;

                    case Reagents.Garlic:
                        sb.Append(ResGeneral.Garlic);

                        break;

                    case Reagents.Ginseng:
                        sb.Append(ResGeneral.Ginseng);

                        break;

                    case Reagents.MandrakeRoot:
                        sb.Append(ResGeneral.MandrakeRoot);

                        break;

                    case Reagents.Nightshade:
                        sb.Append(ResGeneral.Nightshade);

                        break;

                    case Reagents.SulfurousAsh:
                        sb.Append(ResGeneral.SulfurousAsh);

                        break;

                    case Reagents.SpidersSilk:
                        sb.Append(ResGeneral.SpidersSilk);

                        break;

                    // pagan reagents
                    case Reagents.BatWing:
                        sb.Append(ResGeneral.BatWing);

                        break;

                    case Reagents.GraveDust:
                        sb.Append(ResGeneral.GraveDust);

                        break;

                    case Reagents.DaemonBlood:
                        sb.Append(ResGeneral.DaemonBlood);

                        break;

                    case Reagents.NoxCrystal:
                        sb.Append(ResGeneral.NoxCrystal);

                        break;

                    case Reagents.PigIron:
                        sb.Append(ResGeneral.PigIron);

                        break;

                    default:

                        if (Regs[i] < Reagents.None)
                        {
                            sb.Append(StringHelper.AddSpaceBeforeCapital(Regs[i].ToString()));
                        }

                        break;
                    }

                    if (i < Regs.Length - 1)
                    {
                        sb.Append(separator);
                    }
                }

                string ss = sb.ToString();
                sb.Dispose();
                return(ss);
            }
        }
Пример #20
0
        public override void Update(double totalTime, double frameTime)
        {
            base.Update(totalTime, frameTime);

            if (Time.Ticks > _timeToUpdate)
            {
                _timeToUpdate = Time.Ticks + 100;

                GameScene          scene = Client.Game.GetScene <GameScene>();
                Span <char>        span  = stackalloc char[256];
                ValueStringBuilder sb    = new ValueStringBuilder(span);

                if (IsMinimized && scene != null)
                {
                    sb.Append
                        (string.Format(
                            DEBUG_STRING_0,
                            CUOEnviroment.CurrentRefreshRate,
                            0,
                            0,
                            !World.InGame ? 1f : scene.Camera.Zoom,
                            scene.RenderedObjectsCount
                            )
                        );

                    sb.Append($"- CUO version: {CUOEnviroment.Version}, Client version: {Settings.GlobalSettings.ClientVersion}\n");

                    //_sb.AppendFormat(DEBUG_STRING_1, Engine.DebugInfo.MobilesRendered, Engine.DebugInfo.ItemsRendered, Engine.DebugInfo.StaticsRendered, Engine.DebugInfo.MultiRendered, Engine.DebugInfo.LandsRendered, Engine.DebugInfo.EffectsRendered);
                    sb.Append(string.Format(DEBUG_STRING_2, World.InGame ? $"{World.Player.X}, {World.Player.Y}, {World.Player.Z}" : "0xFFFF, 0xFFFF, 0", Mouse.Position, SelectedObject.Object is GameObject gobj ? $"{gobj.X}, {gobj.Y}, {gobj.Z}" : "0xFFFF, 0xFFFF, 0"));

                    sb.Append(string.Format(DEBUG_STRING_3, ReadObject(SelectedObject.Object)));

                    if (CUOEnviroment.Profiler)
                    {
                        double timeDraw = Profiler.GetContext("RenderFrame").TimeInContext;

                        double timeUpdate = Profiler.GetContext("Update").TimeInContext;

                        double timeFixedUpdate = Profiler.GetContext("FixedUpdate").TimeInContext;

                        double timeOutOfContext = Profiler.GetContext("OutOfContext").TimeInContext;

                        //double timeTotalCheck = timeOutOfContext + timeDraw + timeUpdate;
                        double timeTotal = Profiler.TrackedTime;

                        double avgDrawMs = Profiler.GetContext("RenderFrame").AverageTime;

                        sb.Append("- Profiling\n");

                        sb.Append
                        (
                            string.Format
                            (
                                "    Draw:{0:0.0}% Update:{1:0.0}% FixedUpd:{2:0.0} AvgDraw:{3:0.0}ms {4}\n",
                                100d * (timeDraw / timeTotal),
                                100d * (timeUpdate / timeTotal),
                                100d * (timeFixedUpdate / timeTotal),
                                avgDrawMs,
                                CUOEnviroment.CurrentRefreshRate
                            )
                        );
                    }
                }
                else if (scene != null && scene.Camera.Zoom != 1f)
                {
                    sb.Append(string.Format(DEBUG_STRING_SMALL, CUOEnviroment.CurrentRefreshRate, !World.InGame ? 1f : scene.Camera.Zoom));
                }
                else
                {
                    sb.Append(string.Format(DEBUG_STRING_SMALL_NO_ZOOM, CUOEnviroment.CurrentRefreshRate));
                }

                _cacheText = sb.ToString();

                sb.Dispose();

                Vector2 size = Fonts.Bold.MeasureString(_cacheText);

                _alphaBlendControl.Width  = Width = (int)(size.X + 20);
                _alphaBlendControl.Height = Height = (int)(size.Y + 20);

                WantUpdateSize = true;
            }
        }
Пример #21
0
        public unsafe string Translate(int clilocNum, string arg = "", bool capitalize = false)
        {
            string baseCliloc = GetString(clilocNum);

            if (baseCliloc == null)
            {
                return(null);
            }

            if (arg == null)
            {
                arg = "";
            }

            var roChars = arg.AsSpan();


            // get count of valid args
            int i         = 0;
            int totalArgs = 0;
            int trueStart = -1;

            for (; i < roChars.Length; ++i)
            {
                if (roChars[i] != '\t')
                {
                    if (trueStart == -1)
                    {
                        trueStart = i;
                    }
                }
                else if (trueStart >= 0)
                {
                    ++totalArgs;
                }
            }

            if (trueStart == -1)
            {
                trueStart = 0;
            }

            // store index locations
            Point *locations = stackalloc Point[++totalArgs];

            i = trueStart;
            for (int j = 0; i < roChars.Length; ++i)
            {
                if (roChars[i] == '\t')
                {
                    locations[j].X = trueStart;
                    locations[j].Y = i;

                    trueStart = i + 1;

                    ++j;
                }
            }

            bool has_arguments = totalArgs - 1 > 0;

            locations[totalArgs - 1].X = trueStart;
            locations[totalArgs - 1].Y = i;

            ValueStringBuilder sb = new ValueStringBuilder(baseCliloc.AsSpan());
            {
                int index, pos = 0;

                while (pos < sb.Length)
                {
                    int poss = pos;
                    pos = sb.RawChars.Slice(pos, sb.Length - pos).IndexOf('~');

                    if (pos == -1)
                    {
                        break;
                    }

                    pos += poss;

                    int pos2 = sb.RawChars.Slice(pos + 1, sb.Length - (pos + 1)).IndexOf('~');

                    if (pos2 == -1) //non valid arg
                    {
                        break;
                    }

                    pos2 += pos + 1;

                    index = sb.RawChars.Slice(pos + 1, pos2 - (pos + 1)).IndexOf('_');

                    if (index == -1)
                    {
                        //there is no underscore inside the bounds, so we use all the part to get the number of argument
                        index = pos2;
                    }
                    else
                    {
                        index += pos + 1;
                    }

                    int start = pos + 1;
                    int max   = index - start;
                    int count = 0;

                    for (; count < max; count++)
                    {
                        if (!char.IsNumber(sb.RawChars[start + count]))
                        {
                            break;
                        }
                    }

                    if (!int.TryParse(sb.RawChars.Slice(start, count).ToString(), out index))
                    {
                        return($"MegaCliloc: error for {clilocNum}");
                    }

                    --index;

                    var a = index < 0 || index >= totalArgs?string.Empty.AsSpan() : arg.AsSpan().Slice(locations[index].X, locations[index].Y - locations[index].X);

                    if (a.Length > 1)
                    {
                        if (a[0] == '#')
                        {
                            if (int.TryParse(a.Slice(1).ToString(), out int id1))
                            {
                                var ss = GetString(id1);

                                if (string.IsNullOrEmpty(ss))
                                {
                                    a = string.Empty.AsSpan();
                                }
                                else
                                {
                                    a = ss.AsSpan();
                                }
                            }
                        }
                        else if (has_arguments && int.TryParse(a.ToString(), out int clil))
                        {
                            if (_entries.TryGetValue(clil, out string value) && !string.IsNullOrEmpty(value))
                            {
                                a = value.AsSpan();
                            }
                        }
                    }

                    sb.Remove(pos, pos2 - pos + 1);
                    sb.Insert(pos, a);

                    if (index >= 0 && index < totalArgs)
                    {
                        pos += a.Length /*locations[index].Y - locations[index].X*/;
                    }
                }

                baseCliloc = sb.ToString();

                sb.Dispose();

                if (capitalize)
                {
                    baseCliloc = StringHelper.CapitalizeAllWords(baseCliloc);
                }

                return(baseCliloc);
            }
        }
Пример #22
0
        /// <summary>
        /// Try to remove relative segments from the given path (without combining with a root).
        /// </summary>
        /// <param name="skip">Skip the specified number of characters before evaluating.</param>
        internal static string RemoveRelativeSegments(string path, int skip = 0)
        {
            Debug.Assert(skip >= 0);
            bool flippedSeparator = false;

            Span <char>        initialBuffer = stackalloc char[260 /* PathInternal.MaxShortPath */];
            ValueStringBuilder sb            = new ValueStringBuilder(initialBuffer);

            // Remove "//", "/./", and "/../" from the path by copying each character to the output,
            // except the ones we're removing, such that the builder contains the normalized path
            // at the end.
            if (skip > 0)
            {
                sb.Append(path.AsSpan().Slice(0, skip));
            }

            for (int i = skip; i < path.Length; i++)
            {
                char c = path[i];

                if (PathInternal.IsDirectorySeparator(c) && i + 1 < path.Length)
                {
                    // Skip this character if it's a directory separator and if the next character is, too,
                    // e.g. "parent//child" => "parent/child"
                    if (PathInternal.IsDirectorySeparator(path[i + 1]))
                    {
                        continue;
                    }

                    // Skip this character and the next if it's referring to the current directory,
                    // e.g. "parent/./child" => "parent/child"
                    if ((i + 2 == path.Length || PathInternal.IsDirectorySeparator(path[i + 2])) &&
                        path[i + 1] == '.')
                    {
                        i++;
                        continue;
                    }

                    // Skip this character and the next two if it's referring to the parent directory,
                    // e.g. "parent/child/../grandchild" => "parent/grandchild"
                    if (i + 2 < path.Length &&
                        (i + 3 == path.Length || PathInternal.IsDirectorySeparator(path[i + 3])) &&
                        path[i + 1] == '.' && path[i + 2] == '.')
                    {
                        // Unwind back to the last slash (and if there isn't one, clear out everything).
                        int s;
                        for (s = sb.Length - 1; s >= skip; s--)
                        {
                            if (PathInternal.IsDirectorySeparator(sb[s]))
                            {
                                sb.Length = (i + 3 >= path.Length && s == skip) ? s + 1 : s; // to avoid removing the complete "\tmp\" segment in cases like \\?\C:\tmp\..\, C:\tmp\..
                                break;
                            }
                        }
                        if (s < skip)
                        {
                            sb.Length = skip;
                        }

                        i += 2;
                        continue;
                    }
                }

                // Normalize the directory separator if needed
                if (c != PathInternal.DirectorySeparatorChar && c == PathInternal.AltDirectorySeparatorChar)
                {
                    c = PathInternal.DirectorySeparatorChar;
                    flippedSeparator = true;
                }

                sb.Append(c);
            }

            // If we haven't changed the source path, return the original
            if (!flippedSeparator && sb.Length == path.Length)
            {
                sb.Dispose();
                return(path);
            }

            return(sb.ToString());
        }
Пример #23
0
            // Processes the node, adding any prefix text to the builder.
            // Returns whether processing should continue with subsequent nodes.
            static bool Process(RegexNode node, ref ValueStringBuilder vsb)
            {
                if (!StackHelper.TryEnsureSufficientExecutionStack())
                {
                    // If we're too deep on the stack, just give up finding any more prefix.
                    return(false);
                }

                // We don't bother to handle reversed input, so process at most one node
                // when handling RightToLeft.
                bool rtl = (node.Options & RegexOptions.RightToLeft) != 0;

                switch (node.Type)
                {
                // Concatenation
                case RegexNode.Concatenate:
                {
                    int childCount = node.ChildCount();
                    for (int i = 0; i < childCount; i++)
                    {
                        if (!Process(node.Child(i), ref vsb))
                        {
                            return(false);
                        }
                    }
                    return(!rtl);
                }

                // Alternation: find a string that's a shared prefix of all branches
                case RegexNode.Alternate:
                {
                    int childCount = node.ChildCount();

                    // Store the initial branch into the target builder
                    int  initialLength = vsb.Length;
                    bool keepExploring = Process(node.Child(0), ref vsb);
                    int  addedLength   = vsb.Length - initialLength;

                    // Then explore the rest of the branches, finding the length
                    // a prefix they all share in common with the initial branch.
                    if (addedLength != 0)
                    {
                        var alternateSb = new ValueStringBuilder(64);

                        // Process each branch.  If we reach a point where we've proven there's
                        // no overlap, we can bail early.
                        for (int i = 1; i < childCount && addedLength != 0; i++)
                        {
                            alternateSb.Length = 0;

                            // Process the branch.  We want to keep exploring after this alternation,
                            // but we can't if either this branch doesn't allow for it or if the prefix
                            // supplied by this branch doesn't entirely match all the previous ones.
                            keepExploring &= Process(node.Child(i), ref alternateSb);
                            keepExploring &= alternateSb.Length == addedLength;

                            addedLength = Math.Min(addedLength, alternateSb.Length);
                            for (int j = 0; j < addedLength; j++)
                            {
                                if (vsb[initialLength + j] != alternateSb[j])
                                {
                                    addedLength   = j;
                                    keepExploring = false;
                                    break;
                                }
                            }
                        }

                        alternateSb.Dispose();

                        // Then cull back on what was added based on the other branches.
                        vsb.Length = initialLength + addedLength;
                    }

                    return(!rtl && keepExploring);
                }

                // One character
                case RegexNode.One when(node.Options& RegexOptions.IgnoreCase) == 0:
                    vsb.Append(node.Ch);

                    return(!rtl);

                // Multiple characters
                case RegexNode.Multi when(node.Options& RegexOptions.IgnoreCase) == 0:
                    vsb.Append(node.Str);

                    return(!rtl);

                // Loop of one character
                case RegexNode.Oneloop or RegexNode.Oneloopatomic or RegexNode.Onelazy when node.M > 0 && (node.Options & RegexOptions.IgnoreCase) == 0:
                    const int SingleCharIterationLimit = 32;     // arbitrary cut-off to avoid creating super long strings unnecessarily
                    int       count = Math.Min(node.M, SingleCharIterationLimit);
                    vsb.Append(node.Ch, count);
                    return(count == node.N && !rtl);

                // Loop of a node
                case RegexNode.Loop or RegexNode.Lazyloop when node.M > 0:
                {
                    const int NodeIterationLimit = 4;         // arbitrary cut-off to avoid creating super long strings unnecessarily
                    int       limit = Math.Min(node.M, NodeIterationLimit);
                    for (int i = 0; i < limit; i++)
                    {
                        if (!Process(node.Child(0), ref vsb))
                        {
                            return(false);
                        }
                    }
                    return(limit == node.N && !rtl);
                }

                // Grouping nodes for which we only care about their single child
                case RegexNode.Atomic:
                case RegexNode.Capture:
                    return(Process(node.Child(0), ref vsb));

                // Zero-width anchors and assertions
                case RegexNode.Bol:
                case RegexNode.Eol:
                case RegexNode.Boundary:
                case RegexNode.ECMABoundary:
                case RegexNode.NonBoundary:
                case RegexNode.NonECMABoundary:
                case RegexNode.Beginning:
                case RegexNode.Start:
                case RegexNode.EndZ:
                case RegexNode.End:
                case RegexNode.Empty:
                case RegexNode.UpdateBumpalong:
                case RegexNode.Require:
                case RegexNode.Prevent:
                    return(true);

                // Give up for anything else
                default:
                    return(false);
                }
            }
Пример #24
0
        private static void LogPacket(byte[] buffer, int length, bool toServer)
        {
            if (_logFile == null)
            {
                _logFile = new LogFile(FileSystemHelper.CreateFolderIfNotExists(CUOEnviroment.ExecutablePath, "Logs", "Network"), "packets.log");
            }

            Span <char>        span   = stackalloc char[256];
            ValueStringBuilder output = new ValueStringBuilder(span);
            {
                int off = sizeof(ulong) + 2;

                output.Append(' ', off);
                output.Append(string.Format("Ticks: {0} | {1} |  ID: {2:X2}   Length: {3}\n", Time.Ticks, (toServer ? "Client -> Server" : "Server -> Client"), buffer[0], length));

                if (buffer[0] == 0x80 || buffer[0] == 0x91)
                {
                    output.Append(' ', off);
                    output.Append("[ACCOUNT CREDENTIALS HIDDEN]\n");
                }
                else
                {
                    output.Append(' ', off);
                    output.Append("0  1  2  3  4  5  6  7   8  9  A  B  C  D  E  F\n");

                    output.Append(' ', off);
                    output.Append("-- -- -- -- -- -- -- --  -- -- -- -- -- -- -- --\n");

                    ulong address = 0;

                    for (int i = 0; i < length; i += 16, address += 16)
                    {
                        output.Append($"{address:X8}");

                        for (int j = 0; j < 16; ++j)
                        {
                            if ((j % 8) == 0)
                            {
                                output.Append(" ");
                            }

                            if (i + j < length)
                            {
                                output.Append($" {buffer[i + j]:X2}");
                            }
                            else
                            {
                                output.Append("   ");
                            }
                        }

                        output.Append("  ");

                        for (int j = 0; j < 16 && i + j < length; ++j)
                        {
                            byte c = buffer[i + j];

                            if (c >= 0x20 && c < 0x80)
                            {
                                output.Append((char)c);
                            }
                            else
                            {
                                output.Append('.');
                            }
                        }

                        output.Append('\n');
                    }
                }

                output.Append('\n');
                output.Append('\n');

                _logFile.Write(output.ToString());

                output.Dispose();
            }
        }
Пример #25
0
        public static void HandleMessage
        (
            Entity parent,
            string text,
            string name,
            ushort hue,
            MessageType type,
            byte font,
            TextType textType,
            bool unicode = false,
            string lang  = null
        )
        {
            if (string.IsNullOrEmpty(text))
            {
                return;
            }

            Profile currentProfile = ProfileManager.CurrentProfile;

            if (currentProfile != null && currentProfile.OverrideAllFonts)
            {
                font    = currentProfile.ChatFont;
                unicode = currentProfile.OverrideAllFontsIsUnicode;
            }

            switch (type)
            {
            case MessageType.Command:
            case MessageType.Encoded:
            case MessageType.System:
            case MessageType.Party:
                break;

            case MessageType.Guild:
                if (currentProfile.IgnoreGuildMessages)
                {
                    return;
                }
                break;

            case MessageType.Alliance:
                if (currentProfile.IgnoreAllianceMessages)
                {
                    return;
                }
                break;

            case MessageType.Spell:
            {
                //server hue color per default
                if (!string.IsNullOrEmpty(text) && SpellDefinition.WordToTargettype.TryGetValue(text, out SpellDefinition spell))
                {
                    if (currentProfile != null && currentProfile.EnabledSpellFormat && !string.IsNullOrWhiteSpace(currentProfile.SpellDisplayFormat))
                    {
                        ValueStringBuilder sb = new ValueStringBuilder(currentProfile.SpellDisplayFormat.AsSpan());
                        {
                            sb.Replace("{power}".AsSpan(), spell.PowerWords.AsSpan());
                            sb.Replace("{spell}".AsSpan(), spell.Name.AsSpan());

                            text = sb.ToString().Trim();
                        }
                        sb.Dispose();
                    }

                    //server hue color per default if not enabled
                    if (currentProfile != null && currentProfile.EnabledSpellHue)
                    {
                        if (spell.TargetType == TargetType.Beneficial)
                        {
                            hue = currentProfile.BeneficHue;
                        }
                        else if (spell.TargetType == TargetType.Harmful)
                        {
                            hue = currentProfile.HarmfulHue;
                        }
                        else
                        {
                            hue = currentProfile.NeutralHue;
                        }
                    }
                }

                goto case MessageType.Label;
            }

            default:
            case MessageType.Focus:
            case MessageType.Whisper:
            case MessageType.Yell:
            case MessageType.Regular:
            case MessageType.Label:
            case MessageType.Limit3Spell:

                if (parent == null)
                {
                    break;
                }

                // If person who send that message is in ignores list - but filter out Spell Text
                if (IgnoreManager.IgnoredCharsList.Contains(parent.Name) && type != MessageType.Spell)
                {
                    break;
                }

                TextObject msg = CreateMessage
                                 (
                    text,
                    hue,
                    font,
                    unicode,
                    type,
                    textType
                                 );

                msg.Owner = parent;

                if (parent is Item it && !it.OnGround)
                {
                    msg.X          = DelayedObjectClickManager.X;
                    msg.Y          = DelayedObjectClickManager.Y;
                    msg.IsTextGump = true;
                    bool found = false;

                    for (LinkedListNode <Gump> gump = UIManager.Gumps.Last; gump != null; gump = gump.Previous)
                    {
                        Control g = gump.Value;

                        if (!g.IsDisposed)
                        {
                            switch (g)
                            {
                            case PaperDollGump paperDoll when g.LocalSerial == it.Container:
                                paperDoll.AddText(msg);
                                found = true;

                                break;

                            case ContainerGump container when g.LocalSerial == it.Container:
                                container.AddText(msg);
                                found = true;

                                break;

                            case TradingGump trade when trade.ID1 == it.Container || trade.ID2 == it.Container:
                                trade.AddText(msg);
                                found = true;

                                break;
                            }
                        }

                        if (found)
                        {
                            break;
                        }
                    }
                }

                parent.AddMessage(msg);

                break;
            }

            MessageReceived.Raise
            (
                new MessageEventArgs
                (
                    parent,
                    text,
                    name,
                    hue,
                    type,
                    font,
                    textType,
                    unicode,
                    lang
                ),
                parent
            );
        }