Exemple #1
0
            internal static int Process(zlib.ZStream /*!*/ zst, MutableString str, zlib.FlushStrategy flush, bool compress,
                                        out MutableString /*!*/ result, ref MutableString trailingUncompressedData)
            {
                result = MutableString.CreateBinary();

                // add previously compressed data to the output:
                if (zst.next_out != null)
                {
                    result.Append(zst.next_out, 0, zst.next_out_index);
                }

                int err;
                int bufferStart = zst.next_out_index;

                err = Process(zst, str, flush, compress, ref trailingUncompressedData);
                result.Append(zst.next_out, bufferStart, zst.next_out_index - bufferStart);

                if (err == Z_STREAM_END && (flush == zlib.FlushStrategy.Z_FINISH || str == null))
                {
                    err = compress ? zst.deflateEnd() : zst.inflateEnd();
                }

                zst.next_out       = null;
                zst.next_out_index = 0;
                zst.avail_out      = 0;

                return(err);
            }
Exemple #2
0
            public static MutableString Read(GZipReader /*!*/ self, [DefaultProtocol, Optional] int?bytes)
            {
                if (bytes.HasValue && bytes.Value < 0)
                {
                    throw RubyExceptions.CreateArgumentError("negative length -1 given");
                }

                var           stream = self.GetStream();
                MutableString result = MutableString.CreateBinary(self._encoding ?? RubyEncoding.Binary);

                if (bytes.HasValue)
                {
                    int bytesRead = result.Append(stream, bytes.Value);
                    if (bytesRead == 0 && bytes.Value != 0)
                    {
                        return(null);
                    }
                }
                else
                {
                    result.Append(stream);
                }

                return(result);
            }
Exemple #3
0
        public static void SetPreviousByte(StringIO /*!*/ self, [DefaultProtocol] int b)
        {
            // MRI: this checks if the IO is readable although it actually modifies the string:
            MutableString content = self.GetReadableContent();

            int pos = self._position - 1;

            if (pos >= 0)
            {
                int length = content.GetByteCount();
                try {
                    if (pos >= length)
                    {
                        content.Append(0, pos - length);
                        content.Append(unchecked ((byte)b));
                    }
                    else
                    {
                        content.SetByte(pos, unchecked ((byte)b));
                    }
                    self._position = pos;
                } catch (InvalidOperationException) {
                    throw RubyExceptions.CreateIOError("not modifiable string");
                }
            }
        }
Exemple #4
0
        public static MutableString ToJson(MutableString self)
        {
            MutableString result = MutableString.CreateMutable(self.Length + 2, RubyEncoding.UTF8);

            char[] chars          = Encoding.UTF8.GetChars(self.ToByteArray());
            byte[] escapeSequence = new byte[] { (byte)'\\', 0 };
            result.Append('"');
            foreach (char c in chars)
            {
                switch (c)
                {
                case '"':
                case '/':
                case '\\':
                    escapeSequence[1] = (byte)c;
                    result.Append(escapeSequence);
                    break;

                case '\n':
                    escapeSequence[1] = (byte)'n';
                    result.Append(escapeSequence);
                    break;

                case '\r':
                    escapeSequence[1] = (byte)'r';
                    result.Append(escapeSequence);
                    break;

                case '\t':
                    escapeSequence[1] = (byte)'t';
                    result.Append(escapeSequence);
                    break;

                case '\f':
                    escapeSequence[1] = (byte)'f';
                    result.Append(escapeSequence);
                    break;

                case '\b':
                    escapeSequence[1] = (byte)'b';
                    result.Append(escapeSequence);
                    break;

                default:
                    if (c >= 0x20 && c <= 0x7F)
                    {
                        result.Append((byte)c);
                    }
                    else
                    {
                        result.Append(Helpers.EscapeUnicodeChar(c));
                    }
                    break;
                }
            }
            result.Append('"');
            return(result);
        }
Exemple #5
0
 public static void DisplayNumber(float value, MutableString displayValue, uint decimalPlaces = 0, string postFix = "")
 {
     //var numberFormat = MutableString.NumberFormat(decimalPlaces);
     //if (decimalPlaces > 0) {
     displayValue.Append(value, decimalPlaces);
     //} else {
     //  displayValue.Builder.Concat(Mathf.RoundToInt(value));
     //}
     displayValue.Append(postFix);
 }
Exemple #6
0
        /// <summary>
        ///   Takes away all occurences of PreciseTime formatting. Lefts DateTime format.
        /// </summary>
        /// <param name="timeFormat"></param>
        /// <param name="dateTimeFormat"></param>
        /// <param name="preciseTimeFormatAndPosition"></param>
        /// <returns></returns>
        internal static Boolean TakeAwayPreciseTimeFormat(
            String timeFormat,
            out MutableString dateTimeFormat,
            out IDictionary <Int32, String> preciseTimeFormatAndPosition)
        {
            Int32   startPosition, endPosition, caretPosition = 0;
            Boolean isFormatFound = TryFindPreciseTimeFormat(timeFormat, caretPosition, out startPosition, out endPosition);

            if (!isFormatFound)
            {
                dateTimeFormat = null;
                preciseTimeFormatAndPosition = null;
                return(false);
            }

            Dictionary <Int32, String> preciseTimeFormats = new Dictionary <Int32, String>();

            dateTimeFormat = new MutableString();

            Int32 length = endPosition - startPosition + 1;

            preciseTimeFormats.Add(startPosition, timeFormat.Substring(startPosition, length));

            dateTimeFormat.Append(timeFormat.Substring(caretPosition, startPosition - caretPosition));

            caretPosition = endPosition;
            isFormatFound = TryFindPreciseTimeFormat(timeFormat, caretPosition, out startPosition, out endPosition);
            while (isFormatFound)
            {
                length = endPosition - startPosition + 1;
                preciseTimeFormats.Add(startPosition, timeFormat.Substring(startPosition, length));

                dateTimeFormat.Append(timeFormat.Substring(caretPosition + 1, startPosition - caretPosition - 1));

                caretPosition = endPosition;
                isFormatFound = TryFindPreciseTimeFormat(timeFormat, caretPosition, out startPosition, out endPosition);
            }

            // at least length >= 1
            // append the last part of date time format, in case, if it exists.
            if (caretPosition + length < timeFormat.Length)
            {
                dateTimeFormat.Append(timeFormat.Substring(caretPosition + 1));
            }

            preciseTimeFormatAndPosition = preciseTimeFormats;
            return(true);
        }
Exemple #7
0
        void Awake()
        {
            _overviewStr = new MutableString(1024);
            var renderableBindings = _inputMappingsViewModel
                                     .InputMappings
                                     .Select(bindings => {
                return(bindings
                       .Where(binding => RenderableActions.Contains(binding.Id))
                       .OrderBy(binding => RenderableActions.IndexOf(binding.Id)));
            });

            renderableBindings.Subscribe(bindings => {
                _overviewStr.Clear();
                foreach (var binding in bindings)
                {
                    _overviewStr
                    .Append("<i>")
                    .Append(binding.Group)
                    .Append("</i>")
                    .Append(" - ")
                    .Append(binding.Name)
                    .Append(": <b>")
                    .Append(binding.Binding)
                    .Append("</b>")
                    .Append(Environment.NewLine);
                }
                _overviewText.SetMutableString(_overviewStr);
            });
        }
Exemple #8
0
        public static MutableString /*!*/ Read(StringIO /*!*/ self, MutableString buffer, bool eofError)
        {
            var content = self.GetReadableContent();
            int start   = self._position;
            int length  = content.GetByteCount();

            if (buffer != null)
            {
                buffer.Clear();
            }
            else
            {
                buffer = MutableString.CreateBinary();
            }

            if (start < length)
            {
                self._position = length;
                buffer.Append(content, start, length - start).TaintBy(content);
            }
            else if (eofError)
            {
                throw new EOFError("end of file reached");
            }

            return(buffer);
        }
Exemple #9
0
        private void WriteToObject(byte[] /*!*/ buffer, int offset, int count)
        {
            MutableString argument = MutableString.CreateBinary(count);

            argument.Append(buffer, offset, count);
            WriteSite.Target(WriteSite, _io, argument);
        }
Exemple #10
0
        public static MutableString TagUri(RubyContext /*!*/ context, object self)
        {
            MutableString str = MutableString.Create("!ruby/object:");

            str.Append(RubyUtils.GetClassName(context, self));
            return(str);
        }
Exemple #11
0
        public static MutableString Read(StringIO /*!*/ self, [DefaultProtocol] int count, [DefaultProtocol, Optional, NotNull] MutableString buffer)
        {
            var content = self.GetReadableContent();

            if (count < 0)
            {
                throw RubyExceptions.CreateArgumentError("negative length -1 given");
            }

            if (buffer != null)
            {
                buffer.Clear();
            }

            int length = content.GetByteCount();

            if (self._position >= length)
            {
                return(null);
            }

            if (buffer == null)
            {
                buffer = MutableString.CreateBinary();
            }

            int bytesRead = Math.Min(count, length - self._position);

            buffer.Append(content, self._position, bytesRead).TaintBy(content);
            self._position += bytesRead;
            return(buffer);
        }
Exemple #12
0
        private bool LoadFromPath(Scope /*!*/ globalScope, object self, string /*!*/ path, LoadFlags flags)
        {
            Assert.NotNull(globalScope, path);

            ResolvedFile file = FindFile(globalScope, path, (flags & LoadFlags.AppendExtensions) != 0);

            if (file == null)
            {
                throw new LoadError(String.Format("no such file to load -- {0}", path));
            }

            MutableString pathWithExtension = MutableString.Create(path);

            if (file.AppendedExtension != null)
            {
                pathWithExtension.Append(file.AppendedExtension);
            }

            if (AlreadyLoaded(pathWithExtension, flags) || _unfinishedFiles.Contains(pathWithExtension.ToString()))
            {
                return(false);
            }

            try {
                // save path as is, no canonicalization nor combination with an extension or directory:
                _unfinishedFiles.Push(pathWithExtension.ToString());

                if (file.SourceUnit != null)
                {
                    RubyContext rubySource = file.SourceUnit.LanguageContext as RubyContext;
                    if (rubySource != null)
                    {
                        ExecuteRubySourceUnit(file.SourceUnit, globalScope, flags);
                    }
                    else
                    {
                        file.SourceUnit.Execute();
                    }
                }
                else
                {
                    Debug.Assert(file.Path != null);
                    try {
                        Assembly asm = Platform.LoadAssemblyFromPath(Platform.GetFullPath(file.Path));
                        DomainManager.LoadAssembly(asm);
                    } catch (Exception e) {
                        throw new LoadError(e.Message, e);
                    }
                }

                FileLoaded(pathWithExtension, flags);
            } finally {
                _unfinishedFiles.Pop();
            }

            return(true);
        }
Exemple #13
0
        public void HashCodeTest()
        {
            MutableString ar = new MutableString();

            ar.Clear();
            ar.Append("aba");
            ar.Append("caba");
            ar.Append("abacaba");
            MutableString ar1 = new MutableString();

            ar1.Clear();
            ar1.Append("abacaba");
            ar1.Append("abacaba");
            MutableString ar2 = new MutableString();

            ar2.Assign("abacabaabacaba");
            Assert.AreEqual(ar1.GetHashCode(), ar2.GetHashCode());
            Assert.AreEqual(ar1.GetHashCode(), ar.GetHashCode());
        }
Exemple #14
0
        public static MutableString TagUri(RubyStruct /*!*/ self)
        {
            MutableString str          = MutableString.Create("tag:ruby.yaml.org,2002:struct:");
            string        name         = self.Class.Name;
            string        structPrefix = "Struct::";

            if (name.StartsWith(structPrefix))
            {
                name = name.Substring(structPrefix.Length);
            }
            return(str.Append(name));
        }
Exemple #15
0
        public override string ToString()
        {
            MutableString mutableString = new MutableString();

            mutableString.Append("First: ");
            if (First != null)
            {
                mutableString.Append(First.ToString()).Append("; ");
            }
            else
            {
                mutableString.Append("null; ");
            }

            mutableString.Append("Second: ");

            if (Second != null)
            {
                mutableString.Append(Second.ToString());
            }
            else
            {
                mutableString.Append("null");
            }
            return(mutableString.ToString());
        }
Exemple #16
0
        public static RubyArray /*!*/ ReceiveFrom(RubyContext /*!*/ context, RubySocket /*!*/ self, int length, object /*Numeric*/ flags)
        {
            SocketFlags sFlags = ConvertToSocketFlag(context, flags);

            byte[]        buffer   = new byte[length];
            EndPoint      fromEP   = new IPEndPoint(IPAddress.Any, 0);
            int           received = self.Socket.ReceiveFrom(buffer, sFlags, ref fromEP);
            MutableString str      = MutableString.CreateBinary();

            str.Append(buffer, 0, received);
            str.IsTainted = true;
            return(RubyOps.MakeArray2(str, GetAddressArray(context, fromEP)));
        }
Exemple #17
0
        public static MutableString /*!*/ Convert(RubyClass /*!*/ self,
                                                  [DefaultProtocol, NotNull] MutableString /*!*/ toEncoding, [DefaultProtocol, NotNull] MutableString /*!*/ fromEncoding,
                                                  [DefaultProtocol] MutableString str)
        {
            MutableString[] convertedStrings = Convert(toEncoding, fromEncoding, new MutableString[] { str, null });
            MutableString   result           = MutableString.CreateEmpty();

            foreach (MutableString s in convertedStrings)
            {
                result.Append(s);
            }
            return(result);
        }
Exemple #18
0
        public static MutableString /*!*/ ObjectToMutableString(RubyContext /*!*/ context, object obj)
        {
            using (IDisposable handle = RubyUtils.InfiniteInspectTracker.TrackObject(obj)) {
                if (handle == null)
                {
                    return(MutableString.Create("..."));
                }

                MutableString str = MutableString.CreateMutable();
                str.Append("#<");
                str.Append(context.GetClassOf(obj).Name);

                // Ruby prints 2*object_id for objects
                str.Append(':');
                AppendFormatHexObjectId(str, GetObjectId(context, obj));

                // display instance variables
                RubyInstanceData data = context.TryGetInstanceData(obj);
                if (data != null)
                {
                    var  vars  = data.GetInstanceVariablePairs();
                    bool first = true;
                    foreach (KeyValuePair <string, object> var in vars)
                    {
                        if (first)
                        {
                            str.Append(" ");
                            first = false;
                        }
                        else
                        {
                            str.Append(", ");
                        }
                        str.Append(var.Key);
                        str.Append("=");
                        str.Append(RubySites.Inspect(context, var.Value));
                    }
                }
                str.Append(">");

                return(str);
            }
        }
Exemple #19
0
        public static MutableString Receive(RubyContext /*!*/ context, RubyBasicSocket /*!*/ self,
                                            [DefaultProtocol] int length, [DefaultParameterValue(null)] object flags)
        {
            SocketFlags sFlags = ConvertToSocketFlag(context, flags);

            byte[] buffer   = new byte[length];
            int    received = self.Socket.Receive(buffer, 0, length, sFlags);

            MutableString str = MutableString.CreateBinary(received);

            str.Append(buffer, 0, received);
            context.SetObjectTaint(str, true);
            return(str);
        }
Exemple #20
0
        public static MutableString Receive(ConversionStorage <int> /*!*/ fixnumCast, RubyBasicSocket /*!*/ self,
                                            [DefaultProtocol] int length, [DefaultParameterValue(null)] object flags)
        {
            SocketFlags sFlags = ConvertToSocketFlag(fixnumCast, flags);

            byte[] buffer   = new byte[length];
            int    received = self.Socket.Receive(buffer, 0, length, sFlags);

            MutableString str = MutableString.CreateBinary(received);

            str.Append(buffer, 0, received);
            str.IsTainted = true;
            return(str);
        }
Exemple #21
0
        private static IEnumerable <string> PartsWithin(IList <string> parts)
        {
            if (null == parts)
            {
                yield break;
            }

            if (0 == parts.Count)
            {
                yield break;
            }

            foreach (var part in parts)
            {
                yield return(part);
            }

            for (var i = 2; i < parts.Count; i++)
            {
                for (var j = 0; j < parts.Count; j++)
                {
                    if (i + j > parts.Count)
                    {
                        break;
                    }

                    var result = new MutableString();
                    for (var x = j; x < j + i; x++)
                    {
                        result.Append(' ');
                        result.Append(parts[x]);
                    }

                    yield return(result.Trim());
                }
            }
        }
Exemple #22
0
        public static RubyArray /*!*/ ReceiveFrom(ConversionStorage <int> /*!*/ conversionStorage, IPSocket /*!*/ self,
                                                  int length, [DefaultParameterValue(null)] object /*Numeric*/ flags)
        {
            SocketFlags sFlags = ConvertToSocketFlag(conversionStorage, flags);

            byte[]        buffer   = new byte[length];
            EndPoint      fromEP   = new IPEndPoint(IPAddress.Any, 0);
            int           received = self.Socket.ReceiveFrom(buffer, sFlags, ref fromEP);
            MutableString str      = MutableString.CreateBinary();

            str.Append(buffer, 0, received);

            str.IsTainted = true;
            return(RubyOps.MakeArray2(str, self.GetAddressArray(fromEP)));
        }
        public static MutableString /*!*/ TagUri(RubyStruct /*!*/ self)
        {
            MutableString str  = MutableString.CreateMutable("tag:ruby.yaml.org,2002:struct:", self.ImmediateClass.Context.GetIdentifierEncoding());
            string        name = self.ImmediateClass.GetNonSingletonClass().Name;

            if (name != null)
            {
                string structPrefix = "Struct::";
                if (name.StartsWith(structPrefix, StringComparison.Ordinal))
                {
                    name = name.Substring(structPrefix.Length);
                }
            }
            return(str.Append(name));
        }
Exemple #24
0
        public void TestUpperAndLowerCaseMethod()
        {
            MutableString s1 = new MutableString("aza23523aza");
            MutableString s2 = new MutableString("AzA23523Aza");
            MutableString s3 = new MutableString("AZA23523AZA");
            MutableString s4 = new MutableString();

            s1.CopyTo(s4);
            s4.Append("a");
            Assert.IsTrue(s1.ToUpperCase().Equals(s2.ToUpperCase()));
            Assert.IsTrue(s3.Equals(s2));
            s1.Append("a");
            s3.Append("A");
            Assert.IsFalse(s1.Equals(s3));
            Assert.IsTrue(s1.ToLowerCase().Equals(s3.ToLowerCase().ToUpperCase().ToLowerCase()));
            Assert.IsTrue(s1.Equals(s4));
        }
Exemple #25
0
        /// <summary>
        /// If the SCRIPT_LINES__ constant is set, we need to publish the file being loaded,
        /// along with the contents of the file
        /// </summary>
        private void AddScriptLines(SourceUnit file)
        {
            ConstantStorage storage;

            if (!_context.ObjectClass.TryResolveConstant(null, "SCRIPT_LINES__", out storage))
            {
                return;
            }

            IDictionary scriptLines = storage.Value as IDictionary;

            if (scriptLines == null)
            {
                return;
            }

            lock (scriptLines) {
                // Read in the contents of the file

                RubyArray        lines    = new RubyArray();
                SourceCodeReader reader   = file.GetReader();
                RubyEncoding     encoding = RubyEncoding.GetRubyEncoding(reader.Encoding);
                using (reader) {
                    reader.SeekLine(1);
                    while (true)
                    {
                        string lineStr = reader.ReadLine();
                        if (lineStr == null)
                        {
                            break;
                        }
                        MutableString line = MutableString.CreateMutable(lineStr.Length + 1, encoding);
                        line.Append(lineStr).Append('\n');
                        lines.Add(line);
                    }
                }

                // Publish the contents of the file, keyed by the file name
                MutableString path = MutableString.Create(file.Document.FileName, _context.GetPathEncoding());
                scriptLines[path] = lines;
            }
        }
Exemple #26
0
        public void SetData(MeasurementViewData data)
        {
            _leftLinePullGauge.SetPullForce(data.LineColor, data.LeftLinePull);
            _rightLinePullGauge.SetPullForce(data.LineColor, data.RightLinePull);

            _holdLines.color = data.LineColor;
            _holdLines.SetMutableString(data.HoldLines);

            _speedStr
            .Clear()
            .Append("↘ ")
            .Append(data.Speed)
            .Append(" ")
            .Append(data.SpeedUnit);
            _speed.SetValue(_speedStr);

            _speedDetailStr.Clear();
            const string indentation = "    ";

            _speedDetailStr.Append(indentation)
            .Append("→ ")
            .Append(data.HorizontalSpeed)
            .Append(" ")
            .Append(data.SpeedUnit)
            .Append(Environment.NewLine)
            .Append(indentation)
            .Append("↓ ")
            .Append(data.VerticalSpeed)
            .Append(" ")
            .Append(data.SpeedUnit);
            _speedDetail.SetMutableString(_speedDetailStr);

            _altitudeStr
            .Clear()
            .Append("↕ ")
            .Append(data.Altitude)
            .Append(data.AltitudeUnit);
            _altitude.SetValue(_altitudeStr);

            WriteValue(_glideRatio, _glideRatioStr, data.GlideRatio);
            WriteValue(_gforce, _gForceStr, data.GForce);
        }
Exemple #27
0
    private void DrawStatisticsGui()
    {
        GUILayout.Label("Framerate: " + (1f / _smoothDeltaTime));

        const float epsilon      = 0.001f;
        float       maxDeltaTime = 1f / Application.targetFrameRate + epsilon;

        GUILayout.Label("Performance Ratio: " + maxDeltaTime / _deltaTime);

        GUILayout.Label("Fixed Frames: " + _fixedFrameCountGui);

        GUI.color = Color.red;
        _deltaTimeErrorString.Clear();
        for (int i = 0; i < _deltaTimes.Count; i++)
        {
            _deltaTimeErrorString.Append(_deltaTimes[i] > maxDeltaTime ? "|" : " ");
        }
        GUILayout.Label(_deltaTimeErrorString.ToString());
        GUI.color = Color.white;
    }
Exemple #28
0
        public void MutableStringSpanTest()
        {
            char[]        charArray     = { 'a', 'b', 'c', 'd', 'e' };
            Span <char>   testCharSpan  = new Span <char>(charArray);
            MutableString mutableString = new MutableString();

            mutableString.Assign(testCharSpan);
            Assert.AreEqual(5, mutableString.Count);
            Assert.AreEqual("abcde", mutableString.ToString());
            mutableString.Append(testCharSpan);
            Assert.AreEqual(10, mutableString.Count);
            Assert.AreEqual("abcdeabcde", mutableString.ToString());
            mutableString.Insert(5, testCharSpan);
            Assert.AreEqual("abcdeabcdeabcde", mutableString.ToString());
            Span <char> span = new Span <char>(new char[15]);

            mutableString.ToCharArray(span);
            MutableString ar1 = new MutableString(span);

            Assert.AreEqual("abcdeabcdeabcde", ar1.ToString());
        }
Exemple #29
0
        public MutableString addHttpCommand(HttpCommand pCmd)
        {
            pCmd.setLog(LOG);
            pCmd.setInternal(m_bInternal);
            if (!m_bInternal && pCmd.m_strCallback.length() == 0)
            {
                processCommandBase(pCmd);
                return(pCmd.getRetValue());
            }
            else
            {
                if (m_bInternal)
                {
                    lock (getCommandLock())
                    {
                        if (getCommands().isEmpty())
                        {
                            addQueueCommand(pCmd);
                        }
                        else
                        {
                            HttpCommand   cmd      = getCommands().get(0) as HttpCommand;
                            MutableString rString  = cmd.m_params.findHashParam("body") as MutableString;
                            MutableString rString2 = pCmd.m_params.findHashParam("body") as MutableString;

                            rString.Append(rString2);
                        }
                    }
                }
                else
                {
                    addQueueCommand(pCmd);
                }


                start(epLow);

                return(pCmd.getRetValue());
            }
        }
Exemple #30
0
        internal static RubyArray /*!*/ CreateHostEntryArray(RubyContext /*!*/ context, IPHostEntry /*!*/ hostEntry, bool packIpAddresses)
        {
            RubyArray result = new RubyArray(4);

            // host name:
            result.Add(HostNameToMutableString(context, hostEntry.HostName));

            // aliases:
            RubyArray aliases = new RubyArray(hostEntry.Aliases.Length);

            foreach (string alias in hostEntry.Aliases)
            {
                aliases.Add(HostNameToMutableString(context, alias));
            }
            result.Add(aliases);

            // address (the first IPv4):
            foreach (IPAddress address in hostEntry.AddressList)
            {
                if (address.AddressFamily == AddressFamily.InterNetwork)
                {
                    result.Add((int)address.AddressFamily);
                    if (packIpAddresses)
                    {
                        byte[]        bytes = address.GetAddressBytes();
                        MutableString str   = MutableString.CreateBinary();
                        str.Append(bytes, 0, bytes.Length);
                        result.Add(str);
                    }
                    else
                    {
                        result.Add(MutableString.CreateAscii(address.ToString()));
                    }
                    break;
                }
            }
            return(result);
        }
        // returns true if block jumped
        // "result" will be null if there is no successful match
        private static bool BlockReplaceAll(ConversionStorage<MutableString>/*!*/ tosConversion, 
            RubyScope/*!*/ scope, MutableString/*!*/ input, BlockParam/*!*/ block,
            RubyRegex/*!*/ regex, out object blockResult, out MutableString result) {

            var matchScope = scope.GetInnerMostClosureScope();

            var matches = regex.Matches(tosConversion.Context.KCode, input);
            if (matches.Count == 0) {
                result = null;
                blockResult = null;
                matchScope.CurrentMatch = null;
                return false;
            }

            // create an empty result:
            result = input.CreateInstance().TaintBy(input);
            
            int offset = 0;
            foreach (MatchData match in matches) {
                matchScope.CurrentMatch = match;

                input.TrackChanges();
                if (block.Yield(match.GetValue(), out blockResult)) {
                    return true;
                }
                if (input.HasChanged) {
                    return false;
                }

                // resets the $~ scope variable to the last match (skipd if block jumped):
                matchScope.CurrentMatch = match;

                MutableString replacement = Protocols.ConvertToString(tosConversion, blockResult);
                result.TaintBy(replacement);

                // prematch:
                result.Append(input, offset, match.Index - offset);

                // replacement (unlike ReplaceAll, don't interpolate special sequences like \1 in block return value):
                result.Append(replacement);

                offset = match.Index + match.Length;
            }

            // post-last-match:
            result.Append(input, offset, input.Length - offset);

            blockResult = null;
            return false;
        }
Exemple #32
0
        private void AppendRawBytes(MutableString/*!*/ buffer, int count) {
            Debug.Assert(count > 0);

            if (_peekAhead != -1) {
                buffer.Append((byte)_peekAhead);
                _peekAhead = -1;
                count--;
            }
            buffer.Append(_stream, count);
        }
Exemple #33
0
        private static void AppendReplacementExpression(ConversionStorage<MutableString> toS, BinaryOpStorage hashDefault,
            MutableString/*!*/ input, MatchData/*!*/ match, MutableString/*!*/ result, Union<IDictionary<object, object>, MutableString>/*!*/ replacement) {

            if (replacement.Second != null) {
                AppendReplacementExpression(input, match, result, replacement.Second);
            } else {
                Debug.Assert(toS != null && hashDefault != null);

                object replacementObj = HashOps.GetElement(hashDefault, replacement.First, match.GetValue());
                if (replacementObj != null) {
                    var replacementStr = Protocols.ConvertToString(toS, replacementObj);
                    result.Append(replacementStr).TaintBy(replacementStr);
                }
            }
        }
 private static void AppendReplacementExpression(MutableString input, GroupCollection/*!*/ groups, MutableString/*!*/ result, MutableString/*!*/ replacement) {
     int backslashCount = 0;
     for (int i = 0; i < replacement.Length; i++) {
         char c = replacement.GetChar(i);
         if (c == '\\')
             backslashCount++;
         else if (backslashCount == 0)
             result.Append(c);
         else {
             AppendBackslashes(backslashCount, result, 0);
             // Odd number of \'s + digit means insert replacement expression
             if ((backslashCount & 1) == 1) {
                 if (Char.IsDigit(c)) {
                     AppendGroupByIndex(groups, c - '0', backslashCount, result);
                 } else if (c == '&') {
                     AppendGroupByIndex(groups, groups.Count - 1, backslashCount, result);
                 } else if (c == '`') {
                     // Replace with everything in the input string BEFORE the match
                     result.Append(input, 0, groups[0].Index);
                 } else if (c == '\'') {
                     // Replace with everything in the input string AFTER the match
                     int start = groups[0].Index + groups[0].Length;
                     result.Append(input, start, input.Length - start);
                 } else if (c == '+') {
                     // Replace last character in last successful match group
                     AppendLastCharOfLastMatchGroup(groups, result);
                 } else {
                     // unknown escaped replacement char, go ahead and replace untouched
                     result.Append('\\');
                     result.Append(c);
                 }
             } else {
                 // Any other # of \'s or a non-digit character means insert literal \'s and character
                 AppendBackslashes(backslashCount, result, 1);
                 result.Append(c);
             }
             backslashCount = 0;
         }
     }
     AppendBackslashes(backslashCount, result, 1);
 }
 private static void AppendGroupByIndex(GroupCollection/*!*/ groups, int index, int backslashCount, MutableString/*!*/ result) {
     if (groups[index].Success) {
         result.Append(groups[index].Value);
     }
 }
 public static MutableString/*!*/ Reinitialize(MutableString/*!*/ self, [NotNull]byte[] other) {
     self.Clear();
     self.Append(other);
     return self;
 }
        // returns true if block jumped
        // "result" will be null if there is no successful match
        private static bool BlockReplaceAll(RubyScope/*!*/ scope, MutableString/*!*/ input, BlockParam/*!*/ block,
            RubyRegex/*!*/ regex, out object blockResult, out MutableString result) {

            var matchScope = scope.GetInnerMostClosureScope();

            MatchCollection matches = regex.Matches(input);
            if (matches.Count == 0) {
                result = null;
                blockResult = null;
                matchScope.CurrentMatch = null;
                return false;
            }

            // create an empty result:
            result = input.CreateInstance().TaintBy(input);
            
            int offset = 0;
            foreach (Match match in matches) {
                MatchData currentMatch = new MatchData(match, input);
                matchScope.CurrentMatch = currentMatch;

                uint version = input.Version;
                if (block.Yield(MutableString.Create(match.Value), out blockResult)) {
                    return true;
                }
                if (input.Version != version) {
                    return false;
                }

                // resets the $~ scope variable to the last match (skipd if block jumped):
                matchScope.CurrentMatch = currentMatch;

                MutableString replacement = Protocols.ConvertToString(scope.RubyContext, blockResult);
                result.TaintBy(replacement);

                // prematch:
                result.Append(input, offset, match.Index - offset);

                // replacement (unlike ReplaceAll, don't interpolate special sequences like \1 in block return value):
                result.Append(replacement);

                offset = match.Index + match.Length;
            }

            // post-last-match:
            result.Append(input, offset, input.Length - offset);

            blockResult = null;
            return false;
        }
Exemple #38
0
        private static MutableString/*!*/ Append(RubyRegex/*!*/ self, MutableString/*!*/ result) {
            Assert.NotNull(self, result);

            result.Append("(?");
            if (AppendOptionString(result, self.Options, true, false) < 3) {
                result.Append('-');
            }
            AppendOptionString(result, self.Options, false, false);
            result.Append(':');
            AppendEscapeForwardSlash(result, self.GetPattern());
            result.Append(')');
            return result;
        }
Exemple #39
0
        private static void AppendDirectoryName(MutableString/*!*/ result, MutableString/*!*/ name) {
            int resultLength = result.GetCharCount();

            int i;
            for (i = resultLength - 1; i >= 0; i--) {
                if (!IsDirectorySeparator(result.GetChar(i))) {
                    break;
                }
            }

            if (i == resultLength - 1) {
                if (!IsDirectorySeparator(name.GetFirstChar())) {
                    result.Append(DirectorySeparatorChar);
                }
                result.Append(name);
            } else if (IsDirectorySeparator(name.GetFirstChar())) {
                result.Replace(i + 1, resultLength - i - 1, name);
            } else {
                result.Append(name);
            }
        }
Exemple #40
0
        public static void RecursiveJoin(ConversionStorage<MutableString>/*!*/ tosConversion, 
            IList/*!*/ list, MutableString/*!*/ separator, MutableString/*!*/ result, Dictionary<object, bool>/*!*/ seen) {

            Assert.NotNull(list, separator, result, seen);
            // TODO: can we get by only tracking List<> ?
            // (inspect needs to track everything)
            bool found;
            if (seen.TryGetValue(list, out found)) {
                result.Append("[...]");
                return;
            }

            seen.Add(list, true); // push

            for (int i = 0; i < list.Count; ++i) {
                object item = list[i];

                if (item is ValueType) {
                    result.Append(Protocols.ConvertToString(tosConversion, item));
                } else if (item == null) {
                    // append nothing
                } else {
                    IList listItem = item as IList;
                    if (listItem != null) {
                        RecursiveJoin(tosConversion, listItem, separator, result, seen);
                    } else {
                        result.Append(Protocols.ConvertToString(tosConversion, item));
                    }
                }

                if (i < list.Count - 1) {
                    result.Append(separator);
                }
            }

            seen.Remove(list);
        }
Exemple #41
0
        internal static MutableString/*!*/ AppendEscapeForwardSlash(MutableString/*!*/ result, MutableString/*!*/ pattern) {
            int first = 0;
            int i = SkipToUnescapedForwardSlash(pattern, 0);
            while (i >= 0) {
                Debug.Assert(i < pattern.Length);
                Debug.Assert(pattern.GetChar(i) == '/' && (i == 0 || pattern.GetChar(i - 1) != '\\'));

                result.Append(pattern, first, i - first);
                result.Append('\\');
                first = i; // include forward slash in the next append
                i = SkipToUnescapedForwardSlash(pattern, i + 1);
            }

            result.Append(pattern, first, pattern.Length - first);
            return result;
        }
Exemple #42
0
 public MutableString AppendGroupValue(int index, MutableString/*!*/ result) {
     // we don't need to check index range, Groups indexer returns an unsuccessful group if out of range:
     return GroupSuccess(index) ? result.Append(_originalString, GetGroupStart(index), GetGroupLength(index)).TaintBy(this) : null;
 }
Exemple #43
0
        private static int AppendOptionString(MutableString/*!*/ result, RubyRegexOptions options, bool enabled, bool includeEncoding) {
            int count = 0;

            if (((options & RubyRegexOptions.Multiline) != 0) == enabled) {
                result.Append('m');
                count++;
            }

            if (((options & RubyRegexOptions.IgnoreCase) != 0) == enabled) {
                result.Append('i');
                count++;
            }

            if (((options & RubyRegexOptions.Extended) != 0) == enabled) {
                result.Append('x');
                count++;
            }

            if (includeEncoding) {
                switch (options & RubyRegexOptions.EncodingMask) {
                    case RubyRegexOptions.NONE: break;
                    case RubyRegexOptions.EUC: result.Append('e'); break;
                    case RubyRegexOptions.FIXED: result.Append('n'); break;
                    case RubyRegexOptions.UTF8: result.Append('u'); break;
                    case RubyRegexOptions.SJIS: result.Append('s'); break;
                    default: throw Assert.Unreachable;
                }
            }
            return count;
        }
        private void AppendRawBytes(MutableString/*!*/ buffer, int count) {
            Debug.Assert(count > 0);

            int remaining = count;

            if (_bufferCount > 0) {
                int c = Math.Min(_bufferCount, count);
                buffer.Append(_buffer, _bufferStart, c);
                ConsumeBuffered(c);
                remaining -= c;
            }

            if (count == Int32.MaxValue) {
                const int chunk = 1024;

                int done = buffer.GetByteCount();
                int bytesRead;
                do {
                    buffer.Append(_stream, chunk);
                    bytesRead = buffer.GetByteCount() - done;
                    done += bytesRead;
                } while (bytesRead == chunk);
            } else {
                buffer.Append(_stream, remaining);
            }
        }
        private static void AppendLastCharOfLastMatchGroup(MatchData/*!*/ match, MutableString/*!*/ result) {
            int i = match.GroupCount - 1;
            // move to last successful match group
            while (i > 0 && !match.GroupSuccess(i)) {
                i--;
            }

            if (i > 0 && match.GroupSuccess(i)) {
                int length = match.GetGroupLength(i);
                if (length > 0) {
                   result.Append(match.OriginalString, match.GetGroupStart(i) + length - 1, 1);
                }
            }
        }
        private void AppendRawBytes(MutableString/*!*/ buffer, int count) {
            Debug.Assert(count > 0);

            int remaining = count;

            while (_bufferSize > 0) {
                buffer.Append(ReadBufferByte());
                remaining--;
            }

            if (count == Int32.MaxValue) {
                const int chunk = 1024;

                int done = buffer.GetByteCount();
                int bytesRead;
                do {
                    buffer.Append(_stream, chunk);
                    bytesRead = buffer.GetByteCount() - done;
                    done += bytesRead;
                } while (bytesRead == chunk);
            } else {
                buffer.Append(_stream, remaining);
            }
        }
 private static void AppendGroupByIndex(MatchData/*!*/ match, int index, MutableString/*!*/ result) {
     var value = match.GetGroupValue(index);
     if (value != null) {
         result.Append(value);
     }
 }
Exemple #48
0
            internal static int Process(zlib.ZStream/*!*/ zst, MutableString str, zlib.FlushStrategy flush, bool compress,
                out MutableString/*!*/ result, ref MutableString trailingUncompressedData)
            {
                result = MutableString.CreateBinary();

                // add previously compressed data to the output:
                if (zst.next_out != null) {
                    result.Append(zst.next_out, 0, zst.next_out_index);
                }

                int err;
                int bufferStart = zst.next_out_index;
                err = Process(zst, str, flush, compress, ref trailingUncompressedData);
                result.Append(zst.next_out, bufferStart, zst.next_out_index - bufferStart);

                if (err == Z_STREAM_END && (flush == zlib.FlushStrategy.Z_FINISH || str == null)) {
                    err = compress ? zst.deflateEnd() : zst.inflateEnd();
                }

                zst.next_out = null;
                zst.next_out_index = 0;
                zst.avail_out = 0;

                return err;
            }
        public static MutableString ChompInPlace(MutableString/*!*/ self, [DefaultProtocol]MutableString separator) {
            MutableString result = InternalChomp(self, separator);

            if (result.Equals(self) || result == null) {
                return null;
            }

            self.Clear();
            self.Append(result);
            return self;
        }
Exemple #50
0
            private static int Process(zlib.ZStream/*!*/ zst, zlib.FlushStrategy flush, bool compress,
                ref MutableString trailingUncompressedData)
            {
                if (zst.next_out == null) {
                    zst.next_out = new byte[DEFAULTALLOC];
                    zst.next_out_index = 0;
                    zst.avail_out = zst.next_out.Length;
                }

                int result = compress ? zst.deflate(flush) : zst.inflate(flush);

                while (result == Z_OK && zst.avail_out == 0) {
                    byte[] output = zst.next_out;
                    int oldLength = output.Length;

                    Array.Resize(ref output, oldLength * 2);

                    zst.next_out = output;
                    zst.avail_out = oldLength;
                    result = compress ? zst.deflate(flush) : zst.inflate(flush);
                }

                if (!compress && (result == Z_STREAM_END || result == Z_STREAM_ERROR && !zst.IsInitialized)) {
                    // MRI hack: any data left in the stream are saved into a separate buffer and returned when "finish" is called
                    // This is weird behavior, one would expect the rest of the stream is either ignored or copied to the output buffer.
                #if COPY_UNCOMPRESSED_DATA_TO_OUTPUT_BUFFER
                    Debug.Assert(zst.next_in_index + zst.avail_in <= zst.next_in.Length);
                    Debug.Assert(zst.next_out_index + zst.avail_out <= zst.next_out.Length);

                    if (zst.avail_in > zst.avail_out) {
                        byte[] output = zst.next_out;
                        int oldLength = output.Length;

                        Array.Resize(ref output, Math.Max(zst.next_out_index + zst.avail_in, oldLength * 2));
                        zst.next_out = output;
                    }

                    Buffer.BlockCopy(zst.next_in, zst.next_in_index, zst.next_out, zst.next_out_index, zst.avail_in);

                    // MRI subtracts till 0 is reached:
                    zst.avail_out = Math.Max(zst.avail_out - zst.avail_in, 0);
                    zst.next_out_index += zst.avail_in;
                    zst.avail_in = 0;
                #else
                    if (trailingUncompressedData == null) {
                        trailingUncompressedData = MutableString.CreateBinary();
                    }

                    trailingUncompressedData.Append(zst.next_in, zst.next_in_index, zst.avail_in);

                    // MRI subtracts till 0 is reached:
                    zst.avail_out = Math.Max(zst.avail_out - zst.avail_in, 0);
                    zst.avail_in = 0;
                #endif
                    result = Z_STREAM_END;
                }

                return result;
            }
 private static void AppendBackslashes(int backslashCount, MutableString/*!*/ result, int minBackslashes) {
     for (int j = 0; j < ((backslashCount - 1) >> 1) + minBackslashes; j++) {
         result.Append('\\');
     }
 }
        public static MutableString/*!*/ Replace(MutableString/*!*/ self, [DefaultProtocol, NotNull]MutableString/*!*/ other) {
            // Handle case where objects are the same identity
            if (ReferenceEquals(self, other)) {
                return self;
            }

            self.Clear();
            self.Append(other);
            return self.TaintBy(other);
        }
        private static void AppendLastCharOfLastMatchGroup(GroupCollection groups, MutableString result) {
            int i = groups.Count - 1;
            // move to last successful match group
            while (i > 0 && !groups[i].Success) {
                i--;
            }

            if (i > 0 && groups[i].Value.Length > 0) {
                result.Append(groups[i].Value[groups[i].Length - 1]);
            }
        }
 public static MutableString/*!*/ Append(MutableString/*!*/ self, [DefaultProtocol, NotNull]MutableString/*!*/ other) {
     return self.Append(other).TaintBy(other);
 }
        private static MutableString/*!*/ InternalDeleteInPlace(MutableString/*!*/ self, MutableString[]/*!*/ ranges) {
            MutableString result = InternalDelete(self, ranges);
            if (self.Equals(result)) {
                return null;
            }

            self.Clear();
            self.Append(result);
            return self;
        }
Exemple #56
0
        public static MutableString/*!*/ Read(StringIO/*!*/ self, MutableString buffer, bool eofError) {
            var content = self.GetReadableContent();
            int start = self._position;
            int length = content.GetByteCount();

            if (buffer != null) {
                buffer.Clear();
            } else {
                buffer = MutableString.CreateBinary();
            }

            if (start < length) {
                self._position = length;
                buffer.Append(content, start, length - start).TaintBy(content);
            } else if (eofError) {
                throw new EOFError("end of file reached");
            }

            return buffer;
        }
        public static MutableString/*!*/ TrSqueezeInPlace(MutableString/*!*/ self,
            [DefaultProtocol, NotNull]MutableString/*!*/ from, [DefaultProtocol, NotNull]MutableString/*!*/ to) {

            MutableString result = TrInternal(self, from, to, true);
            if (self.Equals(result)) {
                return null;
            }

            self.Clear();
            self.Append(result);
            return self;
        }
Exemple #58
0
 public static MutableString Append(MutableString/*!*/ self, int c)
 {
     return self.Append(Integer.ToChr(self.Encoding, self.Encoding, c));
 }
        public static MutableString/*!*/ Append(MutableString/*!*/ self, int c) {
            if (c < 0 || c > 255) {
                throw RubyExceptions.CreateTypeConversionError("Fixnum", "String");
            }

            return self.Append((byte)c);
        }
Exemple #60
0
        public static MutableString/*!*/ Reinitialize(MutableString/*!*/ self, [DefaultProtocol, NotNull]MutableString other) {
            if (ReferenceEquals(self, other)) {
                return self;
            }

            self.Clear();
            self.Append(other);
            return self.TaintBy(other);
        }