public static int GetServiceByName(RubyClass /*!*/ self, [DefaultProtocol, NotNull] MutableString /*!*/ name, [DefaultProtocol, Optional] MutableString protocol) { if (protocol == null) { protocol = _DefaultProtocol; } ServiceName service = SearchForService(name, protocol); if (service != null) { return(service.Port); } // Cannot use: object port = Protocols.TryConvertToInteger(context, name); // Since the conversion process returns 0 if the string is not a valid number try { return(ParseInteger(self.Context, name.ConvertToString())); } catch (InvalidOperationException) { throw SocketErrorOps.Create( String.Format("no such service {0} {1}", name.ConvertToString(), protocol.ConvertToString()) ); } }
/// <summary> /// Returns <b>true</b> if a Ruby file is successfully loaded, <b>false</b> if it is already loaded. /// </summary> /// <param name="globalScope"> /// A scope against which the file should be executed or null to create a new scope. /// </param> /// <param name="self"></param> /// <param name="path"></param> /// <param name="flags"></param> /// <param name="loaded"></param> /// <returns>True if the file was loaded/executed by this call.</returns> public bool LoadFile(Scope globalScope, object self, MutableString /*!*/ path, LoadFlags flags, out object loaded) { Assert.NotNull(path); string assemblyName, typeName; string strPath = path.ConvertToString(); if (TryParseAssemblyName(strPath, out typeName, out assemblyName)) { if (AlreadyLoaded(strPath, (string)null, flags)) { loaded = ((flags & LoadFlags.ResolveLoaded) != 0) ? GetAssembly(assemblyName, true, false) : null; return(false); } Assembly assembly = LoadAssembly(assemblyName, typeName, false, false); if (assembly != null) { FileLoaded(path.Clone(), flags); loaded = assembly; return(true); } } return(LoadFromPath(globalScope, self, strPath, path.Encoding, flags, out loaded)); }
public static RubyFile/*!*/ CreateFile(RubyClass/*!*/ self, MutableString/*!*/ path, MutableString mode) { if (path.IsEmpty) { throw new Errno.InvalidError(); } return new RubyFile(self.Context, path.ConvertToString(), (mode != null) ? mode.ConvertToString() : "r"); }
public static Digest /*!*/ Initialize(Digest /*!*/ self, [NotNull] MutableString /*!*/ algorithmName) { Crypto.HMAC algorithm; #if SILVERLIGHT switch (algorithmName.ToString()) { case "SHA1": algorithm = new Crypto.HMACSHA1(); break; case "SHA256": algorithm = new Crypto.HMACSHA256(); break; default: algorithm = null; break; } #else algorithm = Crypto.HMAC.Create("HMAC" + algorithmName.ConvertToString()); #endif if (algorithm == null) { throw RubyExceptions.CreateRuntimeError("Unsupported digest algorithm ({0}).", algorithmName); } self._algorithm = algorithm; return(self); }
public static RubyIO CreateIO(RubyClass /*!*/ self, [Optional] MutableString initialString, [Optional] MutableString mode) { MutableStringStream stream = new MutableStringStream(initialString ?? MutableString.CreateBinary()); string ioMode = (mode != null) ? mode.ConvertToString() : "rb+"; return(new StringIO(self.Context, stream, ioMode)); }
private static Socket /*!*/ CreateSocket(MutableString remoteHost, int port) { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { if (remoteHost != null) { socket.Connect(remoteHost.ConvertToString(), port); } else { socket.Connect(IPAddress.Loopback, port); } } catch (SocketException e) { switch (e.SocketErrorCode) { case SocketError.ConnectionRefused: throw new Errno.ConnectionRefusedError(); default: throw; } } return(socket); }
public static Iconv /*!*/ Initialize(Iconv /*!*/ self, [DefaultProtocol] MutableString /*!*/ toEncoding, [DefaultProtocol] MutableString /*!*/ fromEncoding) { self._toEncoding = RubyEncoding.GetEncodingByRubyName(toEncoding.ConvertToString()).GetEncoder(); self._fromEncoding = RubyEncoding.GetEncodingByRubyName(fromEncoding.ConvertToString()).GetDecoder(); return(self); }
public static string /*!*/ MakeMessage(ref MutableString message, string /*!*/ baseMessage) { Assert.NotNull(baseMessage); string result = MakeMessage(message != null ? message.ConvertToString() : null, baseMessage); message = MutableString.Create(result, message != null ? message.Encoding : RubyEncoding.UTF8); return(result); }
public static int Connect(RubyContext /*!*/ context, UDPSocket /*!*/ self, object hostname, object port) { MutableString strHostname = ConvertToHostString(context, hostname); int iPort = ConvertToPortNum(context, port); self.Socket.Connect(strHostname.ConvertToString(), iPort); return(0); }
public static double ConvertStringToFloat(RubyContext context, MutableString value) { try { return(double.Parse(value.ConvertToString(), System.Globalization.CultureInfo.InvariantCulture.NumberFormat)); } catch (FormatException x) { MutableString valueString = RubySites.Inspect(context, value); throw RubyExceptions.CreateArgumentError("invalid value for Float(): " + valueString.ConvertToString(), x); } }
private static TCPSocket /*!*/ BindLocalEndPoint(TCPSocket /*!*/ socket, MutableString localHost, int localPort) { IPAddress localIPAddress = localHost != null?GetHostAddress(localHost.ConvertToString()) : IPAddress.Loopback; IPEndPoint localEndPoint = new IPEndPoint(localIPAddress, localPort); socket.Socket.Bind(localEndPoint); return(socket); }
internal Node Scalar(MutableString taguri, MutableString value, SymbolId style) { return Scalar( taguri != null ? taguri.ConvertToString() : "", value != null ? value.ConvertToString() : "", //It's not clear what style argument really means, it seems to be always :plain //for now we are ignoring it, defaulting to \0 (see Representer class) '\0' ); }
internal static MutableString /*!*/ GetAddressInternal(RubyContext /*!*/ context, object hostname) { // Ruby raises a SocketError rather than the NullReferenceException thrown by .NET if (hostname == null) { throw new SocketException((int)SocketError.HostNotFound); } MutableString strHostname = ConvertToHostString(context, hostname); // If it is an IP address already then just pass it back IPAddress address; if (IPAddress.TryParse(strHostname.ConvertToString(), out address)) { return(strHostname); } // Lookup the host IP address via DNS return(MutableString.Create(Dns.GetHostAddresses(strHostname.ConvertToString())[0].ToString())); }
public static object ParseFile(RubyModule /*!*/ self, [DefaultProtocol, NotNull] MutableString /*!*/ path) { using (Stream stream = new RubyFile(self.Context, path.ConvertToString(), IOMode.Default).GetReadableStream()) { foreach (Node obj in MakeComposer(self.Context, stream)) { return(obj); } } return(ScriptingRuntimeHelpers.False); }
public static object Deserialize(StringConstructor stringConstructor) { if (stringConstructor.Parts.Count > 0) { StringLiteral literal = stringConstructor.Parts[0] as StringLiteral; MutableString mutableString = literal.GetMutableString(); return(mutableString.ConvertToString()); } return(String.Empty); }
public static TCPSocket /*!*/ CreateTCPSocket(RubyClass /*!*/ self, [DefaultProtocol, NotNull] MutableString /*!*/ remoteHost, object remotePort) { int port = ConvertToPortNum(self.Context, remotePort); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(remoteHost.ConvertToString(), port); return(new TCPSocket(self.Context, socket)); }
public static object LoadFile(RubyScope /*!*/ scope, RubyModule /*!*/ self, [DefaultProtocol, NotNull] MutableString /*!*/ path) { using (RubyFile file = new RubyFile(self.Context, path.ConvertToString(), IOMode.Default)) { foreach (object obj in MakeConstructor(scope.GlobalScope, file.GetReadableStream())) { return(obj); } } return(null); }
internal Node Scalar(MutableString taguri, MutableString value, SymbolId style) { return(Scalar( taguri != null ? taguri.ConvertToString() : "", value != null ? value.ConvertToString() : "", //It's not clear what style argument really means, it seems to be always :plain //for now we are ignoring it, defaulting to \0 (see Representer class) '\0' )); }
internal Node Sequence(object self, RubyArray seq) { MutableString taguri = _TagUri.Target(_TagUri, _context, self); object style = _ToYamlStyle.Target(_ToYamlStyle, _context, self); return(Sequence( taguri != null ? taguri.ConvertToString() : "", seq, RubyOps.IsTrue(style) )); }
internal Node Map(object self, Hash map) { MutableString taguri = _TagUri.Target(_TagUri, _context, self); object style = _ToYamlStyle.Target(_ToYamlStyle, _context, self); return(Map( taguri != null ? taguri.ConvertToString() : "", map, RubyOps.IsTrue(style) )); }
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)); }
public static Iconv /*!*/ Initialize(Iconv /*!*/ self, [DefaultProtocol, NotNull] MutableString /*!*/ toEncoding, [DefaultProtocol, NotNull] MutableString /*!*/ fromEncoding) { self._toEncodingString = toEncoding.ConvertToString().ToUpperInvariant(); try { self._toEncoding = RubyEncoding.GetEncodingByRubyName(self._toEncodingString).GetEncoder(); } catch (ArgumentException e) { throw new InvalidEncoding(self._toEncodingString, e); } try { self._fromEncoding = RubyEncoding.GetEncodingByRubyName(fromEncoding.ConvertToString()).GetDecoder(); } catch (ArgumentException e) { throw new InvalidEncoding(fromEncoding.ConvertToString(), e); } self.ResetByteOrderMark(); return(self); }
public static bool IsComplexYaml( CallSiteStorage <Func <CallSite, object, MutableString> > /*!*/ toYamlStyleStorage, CallSiteStorage <Func <CallSite, object, RubyArray> > /*!*/ toYamlPropertiesStorage, MutableString /*!*/ self) { var toYamlStyleSite = toYamlStyleStorage.GetCallSite("to_yaml_style", 0); var toYamlPropertiesSite = toYamlPropertiesStorage.GetCallSite("to_yaml_properties", 0); return(RubyOps.IsTrue(toYamlStyleSite.Target(toYamlStyleSite, self)) || toYamlPropertiesSite.Target(toYamlPropertiesSite, self).Count == 0 || AfterNewLine(self.ConvertToString())); }
public ParserEngineState(Parser parser, RubyScope scope, MutableString source) { Parser = parser; Scope = scope; OriginalSource = source; Source = source.ConvertToString(); CreateID = Helpers.GetCreateId(scope); AllowNaN = DEFAULT_ALLOW_NAN; MaxNesting = DEFAULT_MAX_NESTING; CurrentNesting = 0; Memo = 0; }
public static int Bind(RubyContext /*!*/ context, UDPSocket /*!*/ self, object hostname, object port) { int iPort = ConvertToPortNum(context, port); if (hostname == null) { hostname = MutableString.Create("localhost"); } MutableString address = GetAddressInternal(context, hostname); IPEndPoint ep = new IPEndPoint(IPAddress.Parse(address.ConvertToString()), iPort); self.Socket.Bind(ep); return(0); }
public static object AddDomainType(RubyContext /*!*/ context, BlockParam /*!*/ block, RubyModule /*!*/ self, MutableString /*!*/ domainAndDate, RubyRegex /*!*/ typeRegex) { if (block == null) { throw RubyExceptions.NoBlockGiven(); } MutableString tag = MutableString.Create("tag:"). Append(domainAndDate).Append(":"). Append(typeRegex.GetPattern()); RubyConstructor.AddExternalMultiConstructor(tag.ConvertToString(), block); return(null); }
public static TCPServer /*!*/ CreateTCPServer(RubyClass /*!*/ self, [DefaultProtocol] MutableString hostname, [DefaultParameterValue(null)] object port) { IPAddress listeningInterface = null; if (hostname == null) { listeningInterface = new IPAddress(0); } else { string hostnameStr = hostname.ConvertToString(); if (hostnameStr == IPAddress.Any.ToString()) { listeningInterface = IPAddress.Any; } else if (hostnameStr == IPAddress.Loopback.ToString()) { listeningInterface = IPAddress.Loopback; } else if (!IPAddress.TryParse(hostnameStr, out listeningInterface)) { // look up the host IP from DNS IPHostEntry hostEntry = Dns.GetHostEntry(hostnameStr); foreach (IPAddress address in hostEntry.AddressList) { if (address.AddressFamily == AddressFamily.InterNetwork) { listeningInterface = address; break; } } if (listeningInterface == null) { // TODO: do we need to support any other address family types? // (presumably should support at least IPv6) throw new NotImplementedException("TODO: non-inet addresses"); } } Assert.NotNull(listeningInterface); } Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Bind(new IPEndPoint(listeningInterface, ConvertToPortNum(self.Context, port))); socket.Listen(10); return(new TCPServer(self.Context, socket)); }
public static object OpenIO([NotNull] BlockParam /*!*/ block, RubyClass /*!*/ self, [Optional] MutableString initialString, [Optional] MutableString mode) { MutableStringStream stream = new MutableStringStream(initialString ?? MutableString.CreateBinary()); string ioMode = (mode != null) ? mode.ConvertToString() : "rb+"; RubyIO io = new StringIO(self.Context, stream, ioMode); object result; block.Yield(io, out result); if (!io.Closed) { io.Close(); } return(result); }
public override int Read(char[] /*!*/ buffer, int index, int count) { int read = _str.Length - _pos; if (read > 0) { if (read > count) { read = count; } _str.ConvertToString().CopyTo(_pos, buffer, index, read); _pos += read; } return(read); }
public static MutableString /*!*/ PackInetSockAddr(RubyClass /*!*/ self, object port, object host) { int iPort = ConvertToPortNum(self.Context, port); MutableString strHost = ConvertToHostString(self.Context, host); IPEndPoint ep; IPAddress[] addresses = Dns.GetHostAddresses(strHost.ConvertToString()); if (addresses.Length > 0) { ep = new IPEndPoint(addresses[0], iPort); } else { throw RubyExceptions.CreateArgumentError("invalid host"); } return(MutableString.Create(ep.Serialize().ToString())); }
internal static string /*!*/ ConvertToHostString(MutableString hostName) { if (hostName == null) { throw new SocketException((int)SocketError.HostNotFound); } if (hostName.IsEmpty) { return(IPAddress.Any.ToString()); } else if (hostName.Equals(BROADCAST_STRING)) { return(IPAddress.Broadcast.ToString()); } return(hostName.ConvertToString()); }
public static RubyArray GetAddressInfo(RubyContext /*!*/ context, RubyClass /*!*/ self, object hostname, object port, [DefaultParameterValue(null)] object family, [DefaultParameterValue(0)] object socktype, [DefaultParameterValue(0)] object protocol, [DefaultParameterValue(null)] object flags) { MutableString strHostname = ConvertToHostString(context, hostname); int iPort = ConvertToPortNum(context, port); // Sadly the family, socktype, protocol and flags get passed through at best and ignored at worst, // since System.Net does not provide for them AddressFamily addrFamily = ConvertToAddressFamily(context, family); int socketType = Protocols.CastToFixnum(context, socktype); int protocolType = Protocols.CastToFixnum(context, protocol); RubyArray results = new RubyArray(); IPHostEntry entry = (strHostname != null) ? GetHostEntry(strHostname.ConvertToString()) : MakeEntry(IPAddress.Any); for (int i = 0; i < entry.AddressList.Length; ++i) { IPAddress address = entry.AddressList[i]; RubyArray result = new RubyArray(); result.Add(ToAddressFamilyString(address.AddressFamily)); result.Add(iPort); if (DoNotReverseLookup(context).Value) { result.Add(MutableString.Create(address.ToString())); } else { IPHostEntry alias = GetHostEntry(address); result.Add(MutableString.Create(alias.HostName)); } result.Add(MutableString.Create(address.ToString())); result.Add((int)address.AddressFamily); result.Add(socketType); // TODO: protocol type: result.Add(protocolType); results.Add(result); } return(results); }
public static object ChangeDirectory(BlockParam block, object/*!*/ self, MutableString dir) { string strDir = dir.ConvertToString(); if (block == null) { SetCurrentDirectory(strDir); return 0; } else { string current = Directory.GetCurrentDirectory(); try { SetCurrentDirectory(strDir); object result; block.Yield(dir, out result); return result; } finally { SetCurrentDirectory(current); } } }
public static bool IsComplexYaml(RubyContext/*!*/ context, MutableString/*!*/ self) { return RubyOps.IsTrue(RubyRepresenter.ToYamlStyle(context, self)) || RubyRepresenter.ToYamlProperties(context, self).Count == 0 || AFTER_NEWLINE(self.ConvertToString()); }
public static SymbolId ToSymbol(MutableString/*!*/ self) { return ClrString.ToSymbol(self.ConvertToString()); }
public static MutableString/*!*/ Format(StringFormatterSiteStorage/*!*/ storage, MutableString/*!*/ self, object arg) { IList args = arg as IList ?? new object[] { arg }; StringFormatter formatter = new StringFormatter(storage, self.ConvertToString(), self.Encoding, args); return formatter.Format().TaintBy(self); }
public static object/*!*/ ToIntegerOctal(MutableString/*!*/ self) { return ClrString.ToIntegerOctal(self.ConvertToString()); }
public static double ToDouble(MutableString/*!*/ self) { return ClrString.ToDouble(self.ConvertToString()); }
//write_nonblock #endregion #region read, read_nonblock private static RubyIO/*!*/ OpenFileForRead(RubyContext/*!*/ context, MutableString/*!*/ path) { string strPath = path.ConvertToString(); if (!File.Exists(strPath)) { throw RubyErrno.CreateENOENT(String.Format("No such file or directory - {0}", strPath)); } return new RubyIO(context, File.OpenRead(strPath), "r"); }
internal static string/*!*/ ConvertToHostString(MutableString hostName) { if (hostName == null) { throw new SocketException((int)SocketError.HostNotFound); } if (hostName.IsEmpty) { return IPAddress.Any.ToString(); } else if (hostName.Equals(BROADCAST_STRING)) { return IPAddress.Broadcast.ToString(); } return hostName.ConvertToString(); }
public static string/*!*/ ToClrString(MutableString/*!*/ str) { return str.ConvertToString(); }
public static MutableString/*!*/ Format(RubyContext/*!*/ context, MutableString/*!*/ self, object arg) { IList args = arg as IList; if (args == null) { args = new object[] { arg }; } StringFormatter formatter = new StringFormatter(context, self.ConvertToString(), args); return formatter.Format().TaintBy(self); }
private static string/*!*/ StripWhitespace(MutableString/*!*/ str) { int i = 0; while (i < str.Length) { char c = str.GetChar(i); if (c == ' ' || c == '_' || c == '\t' || c == '\n' || c == '\r') { i += 1; } else { return str.GetSlice(i).ConvertToString().Replace("_", ""); } } return str.ConvertToString().Replace("_", ""); }
private static MutableString/*!*/ DirName(MutableString/*!*/ path) { string strPath = path.ConvertToString(); string directoryName = strPath; if (IsValidPath(strPath)) { strPath = StripPathCharacters(strPath); // handle top-level UNC paths directoryName = Path.GetDirectoryName(strPath); if (directoryName == null) { return MutableString.CreateMutable(strPath, path.Encoding); } string fileName = Path.GetFileName(strPath); if (!String.IsNullOrEmpty(fileName)) { directoryName = StripPathCharacters(strPath.Substring(0, strPath.LastIndexOf(fileName, StringComparison.Ordinal))); } } else { if (directoryName.Length > 1) { directoryName = "//"; } } directoryName = String.IsNullOrEmpty(directoryName) ? "." : directoryName; return MutableString.CreateMutable(directoryName, path.Encoding); }
private void AppendString(MutableString/*!*/ mutable) { string str = mutable.ConvertToString(); if (_opts.Precision != UnspecifiedPrecision && str.Length > _opts.Precision) { str = str.Substring(0, _opts.Precision); } if (!_opts.LeftAdj && _opts.FieldWidth > str.Length) { _buf.Append(' ', _opts.FieldWidth - str.Length); } _buf.Append(str); if (_opts.LeftAdj && _opts.FieldWidth > str.Length) { _buf.Append(' ', _opts.FieldWidth - str.Length); } }
public static Node ToYamlNode(MutableString/*!*/ self, [NotNull]RubyRepresenter/*!*/ rep) { if (RubyOps.IsTrue(_IsBinaryData.Target(_IsBinaryData, rep.Context, self))) { return rep.BaseCreateNode(self.ConvertToBytes()); } string str = self.ConvertToString(); RubyArray props = RubyRepresenter.ToYamlProperties(rep.Context, self); if (props.Count == 0) { MutableString taguri = RubyRepresenter.TagUri(rep.Context, self); char style = (char)0; if (str.StartsWith(":")) { style = '"'; } else { MutableString styleStr = RubyRepresenter.ToYamlStyle(rep.Context, self) as MutableString; if (styleStr != null && styleStr.Length > 0) { style = styleStr.GetChar(0); } } return rep.Scalar(taguri != null ? taguri.ConvertToString() : "", str, style); } Hash map = new Hash(rep.Context); map.Add(MutableString.Create("str"), str); RubyRepresenter.AddYamlProperties(rep.Context, self, map, props); return rep.Map(self, map); }
public static object/*!*/ ToInteger(MutableString/*!*/ self, [DefaultProtocol, DefaultParameterValue(10)]int @base) { return ClrString.ToInteger(self.ConvertToString(), @base); }
private static bool RunIfFileExists(RubyContext/*!*/ context, MutableString/*!*/ path, Func<FileSystemInfo, bool> del) { return RunIfFileExists(context, path.ConvertToString(), del); }
// Looks for RUBYSHELL and then COMSPEC under Windows internal static ProcessStartInfo/*!*/ GetShell(RubyContext/*!*/ context, MutableString/*!*/ command) { PlatformAdaptationLayer pal = context.DomainManager.Platform; string shell = pal.GetEnvironmentVariable("RUBYSHELL"); if (shell == null) { shell = pal.GetEnvironmentVariable("COMSPEC"); } if (shell == null) { string [] commandParts = command.ConvertToString().Split(new char[] { ' ' }, 2); return new ProcessStartInfo(commandParts[0], commandParts.Length == 2 ? commandParts[1] : null); } else { return new ProcessStartInfo(shell, String.Format("/C \"{0}\"", command.ConvertToString())); } }
/// <summary> /// Returns <b>true</b> if a Ruby file is successfully loaded, <b>false</b> if it is already loaded. /// </summary> public bool LoadFile(Scope/*!*/ globalScope, object self, MutableString/*!*/ path, LoadFlags flags) { Assert.NotNull(globalScope, path); string assemblyName, typeName; string strPath = path.ConvertToString(); if (TryParseAssemblyName(strPath, out typeName, out assemblyName)) { if (AlreadyLoaded(path, flags)) { return false; } if (LoadAssembly(assemblyName, typeName, false)) { FileLoaded(path, flags); return true; } } return LoadFromPath(globalScope, self, strPath, flags); }
public static bool IsComplexYaml( CallSiteStorage<Func<CallSite, RubyContext, object, MutableString>>/*!*/ toYamlStyleStorage, CallSiteStorage<Func<CallSite, RubyContext, object, RubyArray>>/*!*/ toYamlPropertiesStorage, RubyContext/*!*/ context, MutableString/*!*/ self) { var toYamlStyleSite = toYamlStyleStorage.GetCallSite("to_yaml_style", 0); var toYamlPropertiesSite = toYamlPropertiesStorage.GetCallSite("to_yaml_properties", 0); return RubyOps.IsTrue(toYamlStyleSite.Target(toYamlStyleSite, context, self)) || toYamlPropertiesSite.Target(toYamlPropertiesSite, context, self).Count == 0 || AfterNewLine(self.ConvertToString()); }
public static string/*!*/ MakeMessage(ref MutableString message, string/*!*/ baseMessage) { Assert.NotNull(baseMessage); string result = MakeMessage(message != null ? message.ConvertToString() : null, baseMessage); message = MutableString.Create(result, message != null ? message.Encoding : RubyEncoding.UTF8); return result; }
public static Node/*!*/ ToYamlNode(UnaryOpStorage/*!*/ isBinaryDataStorage, MutableString/*!*/ self, [NotNull]RubyRepresenter/*!*/ rep) { var site = isBinaryDataStorage.GetCallSite("is_binary_data?"); if (RubyOps.IsTrue(site.Target(site, rep.Context, self))) { return rep.BaseCreateNode(self.ConvertToBytes()); } string str = self.ConvertToString(); RubyArray props = rep.ToYamlProperties(self); if (props.Count == 0) { MutableString taguri = rep.GetTagUri(self); char style = '\0'; if (str.StartsWith(":")) { style = '"'; } else { MutableString styleStr = rep.ToYamlStyle(self); if (styleStr != null && styleStr.Length > 0) { style = styleStr.GetChar(0); } } return rep.Scalar(taguri != null ? taguri.ConvertToString() : "", str, style); } var map = new Dictionary<MutableString, object>() { { MutableString.Create("str"), str } }; rep.AddYamlProperties(self, map, props); return rep.Map(self, map); }
public static double ToDouble(MutableString/*!*/ self) { return Tokenizer.ParseDouble(self.ConvertToString().ToCharArray()); }
private static TCPSocket/*!*/ BindLocalEndPoint(TCPSocket/*!*/ socket, MutableString localHost, int localPort) { IPAddress localIPAddress = localHost != null ? GetHostAddress(localHost.ConvertToString()) : IPAddress.Loopback; IPEndPoint localEndPoint = new IPEndPoint(localIPAddress, localPort); socket.Socket.Bind(localEndPoint); return socket; }
public static SymbolId ToSym(MutableString/*!*/ self) { if (self.IsEmpty) { throw RubyExceptions.CreateArgumentError("interning empty string"); } string str = self.ConvertToString(); // Cannot convert a string that contains null to a symbol if (str.IndexOf('\0') >= 0) { throw RubyExceptions.CreateArgumentError("symbol string may not contain '\0'"); } return SymbolTable.StringToId(str); }
private static Socket/*!*/ CreateSocket(MutableString remoteHost, int port) { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { if (remoteHost != null) { socket.Connect(remoteHost.ConvertToString(), port); } else { socket.Connect(IPAddress.Loopback, port); } } catch (SocketException e) { switch (e.SocketErrorCode) { case SocketError.ConnectionRefused: throw new Errno.ConnectionRefusedError(); default: throw; } } return socket; }
public static double ConvertStringToFloat(RubyContext/*!*/ context, MutableString/*!*/ value) { return RubyOps.ConvertStringToFloat(context, value.ConvertToString()); }
private static MutableString/*!*/ BaseName(MutableString/*!*/ path, MutableString suffix) { if (path.IsEmpty) { return path; } string strPath = path.ConvertToString(); string[] parts = strPath.Split(new[] { DirectorySeparatorChar, AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 0) { return MutableString.CreateMutable(path.Encoding).Append((char)path.GetLastChar()).TaintBy(path); } if (Environment.OSVersion.Platform != PlatformID.Unix && Environment.OSVersion.Platform != PlatformID.MacOSX) { string first = parts[0]; if (strPath.Length >= 2 && IsDirectorySeparator(strPath[0]) && IsDirectorySeparator(strPath[1])) { // UNC: skip 2 parts if (parts.Length <= 2) { return MutableString.CreateMutable(path.Encoding).Append(DirectorySeparatorChar).TaintBy(path); } } else if (first.Length == 2 && Tokenizer.IsLetter(first[0]) && first[1] == ':') { // skip drive letter "X:" if (parts.Length <= 1) { var result = MutableString.CreateMutable(path.Encoding).TaintBy(path); if (strPath.Length > 2) { result.Append(strPath[2]); } return result; } } } string last = parts[parts.Length - 1]; if (MutableString.IsNullOrEmpty(suffix)) { return MutableString.CreateMutable(last, path.Encoding); } StringComparison comparison = Environment.OSVersion.Platform == PlatformID.Unix ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; int matchLength = last.Length; if (suffix != null) { string strSuffix = suffix.ToString(); if (strSuffix.LastCharacter() == '*' && strSuffix.Length > 1) { int suffixIdx = last.LastIndexOf( strSuffix.Substring(0, strSuffix.Length - 1), comparison ); if (suffixIdx >= 0 && suffixIdx + strSuffix.Length <= last.Length) { matchLength = suffixIdx; } } else if (last.EndsWith(strSuffix, comparison)) { matchLength = last.Length - strSuffix.Length; } } return MutableString.CreateMutable(path.Encoding).Append(last, 0, matchLength).TaintBy(path); }