Esempio n. 1
0
        internal static MutableString ConvertToHostString(RubyContext /*!*/ context, object hostname)
        {
            if (hostname == null)
            {
                return(null);
            }
            if (hostname is MutableString)
            {
                MutableString strHostname = (MutableString)hostname;
                // Special cases
                if (strHostname.IsEmpty)
                {
                    strHostname = ANY_IP_STRING;
                }
                else if (strHostname.Equals(BROADCAST_STRING))
                {
                    strHostname = BROADCAST_IP_STRING;
                }
                return(strHostname);
            }
            int iHostname;

            if (Protocols.IntegerAsFixnum(hostname, out iHostname))
            {
                // Ruby uses Little Endian whereas .NET uses Big Endian IP values
                byte[] bytes = new byte[4];
                for (int i = 3; i >= 0; --i)
                {
                    bytes[i]    = (byte)(iHostname & 0xff);
                    iHostname >>= 8;
                }
                return(MutableString.Create(new System.Net.IPAddress(bytes).ToString()));
            }
            return(Protocols.CastToString(context, hostname));
        }
Esempio n. 2
0
        internal static AddressFamily ConvertToAddressFamily(ConversionStorage <MutableString> /*!*/ stringCast, ConversionStorage <int> /*!*/ fixnumCast,
                                                             object family)
        {
            // Default is AF_INET
            if (family == null)
            {
                return(AddressFamily.InterNetwork);
            }
            // If it is a Fixnum then assume it is just the constant value
            if (family is int)
            {
                return((AddressFamily)(int)family);
            }
            // Convert to a string (using to_str) and then look up the value
            MutableString strFamily = Protocols.CastToString(stringCast, family);

            foreach (AddressFamilyName name in FamilyNames)
            {
                if (name.Name.Equals(strFamily))
                {
                    return(name.Family);
                }
            }
            // Convert to a Fixnum (using to_i) and hope it is a valid AddressFamily constant
            return((AddressFamily)Protocols.CastToFixnum(fixnumCast, strFamily));
        }
Esempio n. 3
0
        internal static int ConvertToPortNum(ConversionStorage <MutableString> /*!*/ stringCast, ConversionStorage <int> /*!*/ fixnumCast, object port)
        {
            // conversion protocol: if it's a Fixnum, return it
            // otherwise, convert to string & then convert the result to a Fixnum
            if (port is int)
            {
                return((int)port);
            }

            if (port == null)
            {
                return(0);
            }

            MutableString serviceName = Protocols.CastToString(stringCast, port);
            ServiceName   service     = SearchForService(serviceName);

            if (service != null)
            {
                return(service.Port);
            }

            int i = 0;

            if (Int32.TryParse(serviceName.ToString(), out i))
            {
                return(i);
            }

            throw SocketErrorOps.Create(MutableString.FormatMessage("Invalid port number or service name: `{0}'.", serviceName));
        }
Esempio n. 4
0
        public static int Send(RubyContext /*!*/ context, RubyBasicSocket /*!*/ self, object message, object flags)
        {
            Protocols.CheckSafeLevel(context, 4, "send");
            SocketFlags   socketFlags = ConvertToSocketFlag(context, flags);
            MutableString strMessage  = Protocols.CastToString(context, message);

            return(self.Socket.Send(strMessage.ConvertToBytes(), socketFlags));
        }
Esempio n. 5
0
        public static void SetSocketOption(RubyContext /*!*/ context, RubyBasicSocket /*!*/ self, object /*Numeric*/ level, object /*Numeric*/ optname, object value)
        {
            Protocols.CheckSafeLevel(context, 2, "setsockopt");
            MutableString strValue = Protocols.CastToString(context, value);
            int           iLevel   = Protocols.CastToFixnum(context, Protocols.ConvertToInteger(context, level));
            int           iOptname = Protocols.CastToFixnum(context, Protocols.ConvertToInteger(context, optname));

            self.Socket.SetSocketOption((SocketOptionLevel)iLevel, (SocketOptionName)iOptname, strValue.ConvertToBytes());
        }
Esempio n. 6
0
        public static MutableString Join(ConversionStorage <MutableString> /*!*/ stringCast, RubyClass /*!*/ self, params object[] /*!*/ parts)
        {
            MutableString             result       = MutableString.CreateMutable(RubyEncoding.Binary);
            Dictionary <object, bool> visitedLists = null;
            var           worklist = new Stack <object>();
            int           current  = 0;
            MutableString str;

            Push(worklist, parts);
            while (worklist.Count > 0)
            {
                object part = worklist.Pop();
                var    list = part as IList;
                if (list != null)
                {
                    if (list.Count == 0)
                    {
                        str = MutableString.FrozenEmpty;
                    }
                    else if (visitedLists != null && visitedLists.ContainsKey(list))
                    {
                        str = RubyUtils.InfiniteRecursionMarker;
                    }
                    else
                    {
                        if (visitedLists == null)
                        {
                            visitedLists = new Dictionary <object, bool>(ReferenceEqualityComparer.Instance);
                        }
                        visitedLists.Add(list, true);
                        Push(worklist, list);
                        continue;
                    }
                }
                else if (part == null)
                {
                    throw RubyExceptions.CreateTypeConversionError("NilClass", "String");
                }
                else
                {
                    str = Protocols.CastToString(stringCast, part);
                }

                if (current > 0)
                {
                    AppendDirectoryName(result, str);
                }
                else
                {
                    result.Append(str);
                }
                current++;
            }

            return(result);
        }
Esempio n. 7
0
        private static void Update(ConversionStorage <MutableString> /*!*/ stringCast, Hash /*!*/ values)
        {
            foreach (var pair in values)
            {
                var name  = Protocols.CastToString(stringCast, pair.Key).ToString();
                var value = Protocols.CastToString(stringCast, pair.Value).ToString();

                SetEnvironmentVariable(stringCast.Context, name, value);
            }
        }
Esempio n. 8
0
        public static int Send(RubyContext /*!*/ context, RubyBasicSocket /*!*/ self, object message, object flags, object hostname, object port)
        {
            Protocols.CheckSafeLevel(context, 4, "send");
            // Convert the parameters
            SocketFlags   sFlags     = ConvertToSocketFlag(context, flags);
            MutableString strMessage = Protocols.CastToString(context, message);
            MutableString address    = GetAddressInternal(context, hostname);
            int           iPort      = ConvertToPortNum(context, port);
            EndPoint      toEndPoint = new IPEndPoint(IPAddress.Parse(address.ConvertToString()), iPort);

            return(self.Socket.SendTo(strMessage.ConvertToBytes(), sFlags, toEndPoint));
        }
Esempio n. 9
0
        /// <summary>
        /// Step through a Range of Strings.
        /// </summary>
        /// <remarks>
        /// This method requires step to be a Fixnum.
        /// It uses a hybrid string comparison to prevent infinite loops and calls String#succ to get each item in the range.
        /// </remarks>
        private static object StepString(
            ConversionStorage <MutableString> /*!*/ stringCast,
            BinaryOpStorage /*!*/ comparisonStorage,
            BinaryOpStorage /*!*/ lessThanStorage,
            BinaryOpStorage /*!*/ greaterThanStorage,
            UnaryOpStorage /*!*/ succStorage,
            BlockParam block, Range /*!*/ self, MutableString begin, MutableString end, int step)
        {
            CheckStep(step);
            object        result;
            MutableString item = begin;
            int           comp;

            var succSite = succStorage.GetCallSite("succ");

            while ((comp = Protocols.Compare(comparisonStorage, lessThanStorage, greaterThanStorage, item, end)) < 0)
            {
                if (block == null)
                {
                    throw RubyExceptions.NoBlockGiven();
                }

                if (block.Yield(item, out result))
                {
                    return(result);
                }

                for (int i = 0; i < step; i++)
                {
                    item = Protocols.CastToString(stringCast, succSite.Target(succSite, item));
                }

                if (item.Length > end.Length)
                {
                    return(self);
                }
            }

            if (comp == 0 && !self.ExcludeEnd)
            {
                if (block == null)
                {
                    throw RubyExceptions.NoBlockGiven();
                }

                if (block.Yield(item, out result))
                {
                    return(result);
                }
            }
            return(self);
        }
        private static List <KeyValuePair <string, string> > ExtractHash(RubyContext /*!*/ context, Hash /*!*/ values)
        {
            var result = new List <KeyValuePair <string, string> >(values.Count);

            foreach (var pair in values)
            {
                result.Add(new KeyValuePair <string, string>(
                               Protocols.CastToString(context, pair.Key).ToString(),
                               Protocols.CastToString(context, pair.Value).ToString()
                               ));
            }
            return(result);
        }
Esempio n. 11
0
 public static Win32API /*!*/ Reinitialize(
     ConversionStorage <MutableString> /*!*/ toStr,
     Win32API /*!*/ self,
     [DefaultProtocol, NotNull] MutableString /*!*/ libraryName,
     [DefaultProtocol, NotNull] MutableString /*!*/ functionName,
     [NotNull] IList /*!*/ parameterTypes,
     [DefaultProtocol, NotNull] MutableString /*!*/ returnType)
 {
     return(self.Reinitialize(
                GetFunction(libraryName, functionName),
                MakeSignature(parameterTypes.Count, (i) => {
         var str = Protocols.CastToString(toStr, parameterTypes[i]);
         return str.IsEmpty ? (byte)0 : str.GetByte(0);
     }),
                returnType.IsEmpty ? ArgType.None : ToArgType(returnType.GetByte(0))
                ));
 }
Esempio n. 12
0
        public static int Send(RubyContext /*!*/ context, RubyBasicSocket /*!*/ self, object message, object flags, object to)
        {
            Protocols.CheckSafeLevel(context, 4, "send");
            // Convert the parameters
            SocketFlags   socketFlags  = ConvertToSocketFlag(context, flags);
            MutableString strMessage   = Protocols.CastToString(context, message);
            MutableString strToAddress = Protocols.CastToString(context, to);
            // Unpack the socket address information from the to parameter
            SocketAddress address = new SocketAddress(AddressFamily.InterNetwork);

            for (int i = 0; i < strToAddress.GetByteCount(); i++)
            {
                address[i] = strToAddress.GetByte(i);
            }
            EndPoint toEndPoint = self.Socket.LocalEndPoint.Create(address);

            return(self.Socket.SendTo(strMessage.ConvertToBytes(), socketFlags, toEndPoint));
        }
Esempio n. 13
0
        public IOInfo AddOptions(ConversionStorage <MutableString> /*!*/ toStr, IDictionary <object, object> options)
        {
            var context = toStr.Context;

            IOInfo result = this;
            object optionValue;

            if (options.TryGetValue(context.CreateAsciiSymbol("encoding"), out optionValue))
            {
                result = result.AddEncoding(context, Protocols.CastToString(toStr, optionValue));
            }

            if (options.TryGetValue(context.CreateAsciiSymbol("mode"), out optionValue))
            {
                result = result.AddModeAndEncoding(context, Protocols.CastToString(toStr, optionValue));
            }

            return(result);
        }
Esempio n. 14
0
        public static RubyRegex /*!*/ Union(ConversionStorage <MutableString> /*!*/ stringCast, ConversionStorage <IList> /*!*/ toAry, RubyClass /*!*/ self, [NotNull] object /*!*/ obj)
        {
            IList list = Protocols.TryCastToArray(toAry, obj);

            if (list != null)
            {
                return(Union(stringCast, list));
            }

            // TODO: to_regexp
            RubyRegex regex = obj as RubyRegex;

            if (regex != null)
            {
                return(regex);
            }

            return(new RubyRegex(RubyRegex.Escape(Protocols.CastToString(stringCast, obj)), RubyRegexOptions.NONE));
        }
Esempio n. 15
0
        internal static string /*!*/ ConvertToHostString(ConversionStorage <MutableString> /*!*/ stringCast, object hostName)
        {
            BigInteger bignum;

            if (hostName is int)
            {
                return(ConvertToHostString((int)hostName));
            }
            else if (!ReferenceEquals(bignum = hostName as BigInteger, null))
            {
                return(ConvertToHostString(bignum));
            }
            else if (hostName != null)
            {
                return(ConvertToHostString(Protocols.CastToString(stringCast, hostName)));
            }
            else
            {
                return(ConvertToHostString((MutableString)null));
            }
        }
Esempio n. 16
0
        internal static int ConvertToPortNum(RubyContext /*!*/ context, object port)
        {
            // conversion protocol: if it's a Fixnum, return it
            // otherwise, convert to string & then convert the result to a Fixnum
            if (port is int)
            {
                return((int)port);
            }

            MutableString serviceName = Protocols.CastToString(context, port);
            ServiceName   service     = SearchForService(serviceName);

            if (service != null)
            {
                return(service.Port);
            }

            int result;

            Protocols.IntegerAsFixnum(Protocols.ConvertToInteger(context, serviceName), out result);
            return(result);
        }
Esempio n. 17
0
        private static RubyRegex /*!*/ Union(ConversionStorage <MutableString> /*!*/ stringCast, ICollection /*!*/ objs)
        {
            if (objs.Count == 0)
            {
                return(new RubyRegex(MutableString.CreateAscii("(?!)"), RubyRegexOptions.NONE));
            }

            MutableString result = MutableString.CreateMutable(RubyEncoding.Binary);
            int           i      = 0;

            foreach (var obj in objs)
            {
                if (i > 0)
                {
                    result.Append('|');
                }

                // TODO: to_regexp
                RubyRegex regex = obj as RubyRegex;
                if (regex != null)
                {
                    if (objs.Count == 1)
                    {
                        return(regex);
                    }

                    regex.AppendTo(result);
                }
                else
                {
                    result.Append(RubyRegex.Escape(Protocols.CastToString(stringCast, obj)));
                }

                i++;
            }

            return(new RubyRegex(result, RubyRegexOptions.NONE));
        }
Esempio n. 18
0
        public static RubyRegex /*!*/ Union(ConversionStorage <MutableString> /*!*/ stringCast, RubyClass /*!*/ self, params object[] /*!*/ strings)
        {
            if (strings.Length == 0)
            {
                return(new RubyRegex(MutableString.CreateAscii("(?!)"), RubyRegexOptions.NONE));
            }

            MutableString result = MutableString.CreateMutable(RubyEncoding.Binary);

            for (int i = 0; i < strings.Length; i++)
            {
                if (i > 0)
                {
                    result.Append('|');
                }

                RubyRegex regex = strings[i] as RubyRegex;
                if (regex != null)
                {
                    if (strings.Length == 1)
                    {
                        return(regex);
                    }

                    regex.AppendTo(result);
                }
                else
                {
                    result.Append(RubyRegex.Escape(Protocols.CastToString(stringCast, strings[i])));
                }
            }

            // TODO:
            //RubyClass regexClass = RubyUtils.GetExecutionContext(context).GetClass(typeof(RubyRegex));
            //return NewCallSite3.Invoke(context, regexClass, result, null, null);
            return(new RubyRegex(result, RubyRegexOptions.NONE));
        }
Esempio n. 19
0
 internal static FileSystemInfo /*!*/ Create(RubyContext /*!*/ context, object path)
 {
     return(Create(context, Protocols.CastToString(context, path).ConvertToString()));
 }
Esempio n. 20
0
        public static object Open(BlockParam /*!*/ block, RubyClass /*!*/ self, object path, int fileMode, int permissions)
        {
            RubyIO io = RubyIOOps._CreateIOSharedSite5.Target(RubyIOOps._CreateIOSharedSite5, self.Context, self, Protocols.CastToString(self.Context, path), fileMode, permissions);

            return(RubyIOOps.TryInvokeOpenBlock(self.Context, block, io));
        }
Esempio n. 21
0
        public static object Open(BlockParam /*!*/ block, RubyClass /*!*/ self, object path)
        {
            RubyIO io = RubyIOOps._CreateIOSharedSite3.Target(RubyIOOps._CreateIOSharedSite3, self.Context, self, Protocols.CastToString(self.Context, path));

            return(RubyIOOps.TryInvokeOpenBlock(self.Context, block, io));
        }
Esempio n. 22
0
 private static RubyEncoding ToEncoding(ConversionStorage <MutableString> /*!*/ toStr, object obj)
 {
     return((obj == null) ? null :
            obj as RubyEncoding ??
            RubyEncoding.GetRubyEncoding(Protocols.CastToString(toStr, obj).ToString())); // TODO: ToString
 }
Esempio n. 23
0
        public static object Open(RubyContext /*!*/ context, BlockParam /*!*/ block, RubyClass /*!*/ self, int fileDescriptor, object mode)
        {
            RubyIO io = _CreateIOSharedSite11.Target(_CreateIOSharedSite11, context, self, fileDescriptor, Protocols.CastToString(context, mode));

            return(TryInvokeOpenBlock(context, block, io));
        }
Esempio n. 24
0
 public static object ImplicitMatch(ConversionStorage <MutableString> /*!*/ stringCast, RubyScope /*!*/ scope, RubyRegex /*!*/ self)
 {
     return(MatchIndex(scope, self, Protocols.CastToString(stringCast, scope.GetInnerMostClosureScope().LastInputLine)));
 }
Esempio n. 25
0
 public static object ImplicitMatch(RubyScope /*!*/ scope, RubyRegex /*!*/ self)
 {
     return(MatchIndex(scope, self, Protocols.CastToString(scope.RubyContext, scope.GetInnerMostClosureScope().LastInputLine)));
 }
Esempio n. 26
0
        public static MutableString /*!*/ Pack(RubyContext /*!*/ context, RubyArray /*!*/ self, [DefaultProtocol, NotNull] MutableString /*!*/ format)
        {
            using (MutableStringStream stream = new MutableStringStream()) {
                BinaryWriter writer = new BinaryWriter(stream);
                int          i      = 0;
                foreach (FormatDirective directive in FormatDirective.Enumerate(format.ConvertToString()))
                {
                    int remaining = (self.Count - i);
                    int count     = directive.Count.HasValue ? directive.Count.Value : remaining;
                    if (count > remaining)
                    {
                        count = remaining;
                    }

                    MutableString str;
                    switch (directive.Directive)
                    {
                    case '@':
                        count           = 0;
                        stream.Position = directive.Count.HasValue ? directive.Count.Value : 1;
                        break;

                    case 'A':
                    case 'a':
                    case 'Z':
                        count = 1;
                        char[] cstr = Protocols.CastToString(context, self[i]).ToString().ToCharArray();
                        int    len1 = directive.Count.HasValue ? directive.Count.Value : cstr.Length;
                        int    len2 = (len1 > cstr.Length) ? cstr.Length : len1;
                        writer.Write(cstr, 0, len2);
                        if (len1 > len2)
                        {
                            byte fill = (directive.Directive == 'A') ? (byte)' ' : (byte)0;
                            for (int j = 0; j < (len1 - len2); j++)
                            {
                                writer.Write(fill);
                            }
                        }
                        if (directive.Directive == 'Z' && !directive.Count.HasValue)
                        {
                            writer.Write((byte)0);
                        }
                        break;

                    case 'Q':
                    case 'q':
                        for (int j = 0; j < count; j++)
                        {
                            writer.Write(Protocols.CastToUInt64Unchecked(context, self[i + j]));
                        }
                        break;

                    case 'l':
                    case 'i':
                        for (int j = 0; j < count; j++)
                        {
                            writer.Write(unchecked ((int)Protocols.CastToUInt32Unchecked(context, self[i + j])));
                        }
                        break;

                    case 'L':
                    case 'I':
                        for (int j = 0; j < count; j++)
                        {
                            writer.Write(Protocols.CastToUInt32Unchecked(context, self[i + j]));
                        }
                        break;

                    case 'N':     // unsigned 4-byte big-endian
                        WriteUInt32(writer, self, context, i, count, BitConverter.IsLittleEndian);
                        break;

                    case 'n':     // unsigned 2-byte big-endian
                        WriteUInt16(writer, self, context, i, count, BitConverter.IsLittleEndian);
                        break;

                    case 'V':     // unsigned 4-byte little-endian
                        WriteUInt32(writer, self, context, i, count, !BitConverter.IsLittleEndian);
                        break;

                    case 'v':     // unsigned 2-byte little-endian
                        WriteUInt16(writer, self, context, i, count, !BitConverter.IsLittleEndian);
                        break;

                    case 's':
                        for (int j = 0; j < count; j++)
                        {
                            writer.Write(unchecked ((short)Protocols.CastToUInt32Unchecked(context, self[i + j])));
                        }
                        break;

                    case 'S':
                        for (int j = 0; j < count; j++)
                        {
                            writer.Write(unchecked ((ushort)Protocols.CastToUInt32Unchecked(context, self[i + j])));
                        }
                        break;

                    case 'c':
                        for (int j = 0; j < count; j++)
                        {
                            writer.Write(unchecked ((sbyte)Protocols.CastToUInt32Unchecked(context, self[i + j])));
                        }
                        break;

                    case 'C':
                        for (int j = 0; j < count; j++)
                        {
                            writer.Write(unchecked ((byte)Protocols.CastToUInt32Unchecked(context, self[i + j])));
                        }
                        break;

                    case 'm':
                        count = 1;
                        str   = Protocols.CastToString(context, self[i]);
                        char[] base64 = Convert.ToBase64String(str.ToByteArray()).ToCharArray();
                        for (int j = 0; j < base64.Length; j += 60)
                        {
                            int len = base64.Length - j;
                            if (len > 60)
                            {
                                len = 60;
                            }
                            writer.Write(base64, j, len);
                            writer.Write('\n');
                        }
                        break;

                    case 'U':
                        char[] buffer = new char[count];
                        for (int j = 0; j < count; j++)
                        {
                            buffer[j] = unchecked ((char)Protocols.CastToUInt32Unchecked(context, self[i + j]));
                        }
                        writer.Write(Encoding.UTF8.GetBytes(buffer));
                        break;

                    case 'X':
                        count = 0;
                        int len3 = directive.Count.HasValue ? directive.Count.Value : 0;
                        if (len3 > stream.Position)
                        {
                            throw RubyExceptions.CreateArgumentError("X outside of string");
                        }
                        stream.Position -= len3;
                        break;

                    case 'x':
                        count = 0;
                        int len4 = directive.Count.HasValue ? directive.Count.Value : 0;
                        for (int j = 0; j < len4; j++)
                        {
                            writer.Write((byte)0);
                        }
                        break;

                    case 'h':
                    case 'H':
                        // MRI skips null, unlike in "m" directive:
                        if (self[i] != null)
                        {
                            str = Protocols.CastToString(context, self[i]);
                            FromHex(writer, str, directive.Count ?? str.GetByteCount(), directive.Directive == 'h');
                        }
                        break;

                    default:
                        throw RubyExceptions.CreateArgumentError(
                                  String.Format("Unknown format directive '{0}'", directive.Directive));
                    }
                    i += count;
                    if (i >= self.Count)
                    {
                        break;
                    }
                }
                stream.SetLength(stream.Position);
                return(stream.String);
            }
        }