public override void Write(ulong value)
        {
            fixed(byte *p = buffer)
            BigEndian.WriteInt64(p, (long)value);

            OutStream.Write(buffer, 0, 8);
        }
Beispiel #2
0
        public override void Write(ulong value)
        {
            if (IsBigEndian)
            {
                dataBuffer[0] = (byte)(value >> 56);
                dataBuffer[1] = (byte)(value >> 48);
                dataBuffer[2] = (byte)(value >> 40);
                dataBuffer[3] = (byte)(value >> 32);

                dataBuffer[4] = (byte)(value >> 24);
                dataBuffer[5] = (byte)(value >> 16);
                dataBuffer[6] = (byte)(value >> 8);
                dataBuffer[7] = (byte)(value);
            }
            else
            {
                dataBuffer[0] = (byte)(value);
                dataBuffer[1] = (byte)(value >> 8);
                dataBuffer[2] = (byte)(value >> 16);
                dataBuffer[3] = (byte)(value >> 24);

                dataBuffer[4] = (byte)(value >> 32);
                dataBuffer[5] = (byte)(value >> 40);
                dataBuffer[6] = (byte)(value >> 48);
                dataBuffer[7] = (byte)(value >> 56);
            }

            OutStream.Write(dataBuffer, 0, sizeof(ulong));
        }
Beispiel #3
0
        private void PrintField(string s, int max, bool isHeader, char padding, char extrachar)
        {
            int leftlen;
            int rightlen;

            if (s == null)
            {
                s         = "";
                padding   = EmptyFieldDelimiter;
                extrachar = EmptyFieldDelimiter;
            }
            CalculateBuffer(max, s.Length, out leftlen, out rightlen);

            if (PrintFieldGutters)
            {
                OutStream.Write(extrachar);
            }

            OutStream.Write(new string(padding, leftlen));
            OutStream.Write(s);
            OutStream.Write(new string(padding, rightlen));

            if (PrintFieldGutters)
            {
                OutStream.Write(extrachar);
            }
        }
Beispiel #4
0
        /// <summary>
        /// Header consists of:
        /// 1) |---------------------| <-- hyphen line
        /// 2) |    |    | 5     | 1 | <-- (optional) max width of field
        /// 3) | LN | FC | 1     | 2 | <-- field number
        /// 4) |    |    | line3 | c | <-- (optional) header field
        /// 5) |-----------------+---| <-- hyphen line
        ///     (a) optional line number
        ///           (b) optional field count for each row
        /// </summary>
        private void PrintHeader()
        {
            // (1)
            // print top line
            PrintHyphenLine(false);

            // (2)
            if (PrintFieldMaxWidth)
            {
                PrintLineNumberField("FS");
                PrintFieldCountField("");

                for (int i = 0; i < MaxFieldCount; ++i)
                {
                    OutStream.Write("|");
                    PrintField(MaxFieldLengths[i].ToString(), MaxFieldLengths[i], true);
                }
                OutStream.Write("|" + System.Environment.NewLine);
            }

            // (3)
            {
                PrintLineNumberField("LN");
                PrintFieldCountField("FC");

                // print field numbers
                for (int i = 0; i < MaxFieldCount; ++i)
                {
                    OutStream.Write('|');
                    PrintField((FieldOffset + i).ToString(), MaxFieldLengths[i], true);
                }
                OutStream.Write("|" + System.Environment.NewLine);
            }

            // (4) print headers (if we need them)
            if (Header == PrintHeaderType.PrintRow1 || Header == PrintHeaderType.PrintExternFile)
            {
                string[] fields = ParseClass.ParseLine(HeaderLine, TrimFields, Delimiter, PreserveQuotes);

                PrintLineNumberField("");
                PrintFieldCountField(fields.Length.ToString());

                for (int i = 0; i < MaxFieldCount; ++i)
                {
                    OutStream.Write("|");
                    if (i >= fields.Length)
                    {
                        PrintField(null, MaxFieldLengths[i], true);
                    }
                    else
                    {
                        PrintField(fields[i], MaxFieldLengths[i], true);
                    }
                }
                OutStream.Write("|" + System.Environment.NewLine);
            }

            // (5) print plus line between header & body
            PrintHyphenLine(true);
        }
Beispiel #5
0
        private void PrintHyphenLine(bool includePlus)
        {
            char hyphen       = '-';
            char openingchar  = '-';
            char fielddivider = (includePlus ? '+' : '-');

            if (PrintLineNumber)
            {
                OutStream.Write(openingchar);
                openingchar = fielddivider;
                PrintField("", LengthOfMaxLineNumber, true, hyphen, hyphen);
            }
            if (PrintFieldCount)
            {
                OutStream.Write(openingchar);
                openingchar = fielddivider;
                PrintField("", LengthOfMaxFieldCount, true, hyphen, hyphen);
            }
            for (int i = 0; i < MaxFieldCount; ++i)
            {
                OutStream.Write((i == 0) ? openingchar : fielddivider);
                PrintField("", MaxFieldLengths[i], true, hyphen, hyphen);
            }
            OutStream.Write("|" + System.Environment.NewLine);
        }
        public override void Write(ushort value)
        {
            fixed(byte *p = buffer)
            BigEndian.WriteInt16(p, (short)value);

            OutStream.Write(buffer, 0, 2);
        }
Beispiel #7
0
        public void WriteDirectoryEntry(string path, string username, string groupname, int mode, DateTime lastModificationTime)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }

            if (path[path.Length - 1] != '/')
            {
                path += '/';
            }

            var tarHeader = new UsTarHeader()
            {
                FileName         = path,
                LastModification = lastModificationTime,
                SizeInBytes      = 0,
                UserId           = username.GetHashCode(),
                UserName         = username,
                GroupId          = groupname.GetHashCode(),
                GroupName        = groupname,
                Mode             = mode,
                EntryType        = tar_cs.EntryType.Directory,
            };

            OutStream.Write(tarHeader.GetHeaderValue(), 0, tarHeader.HeaderSize);
        }
Beispiel #8
0
        // Builder parameters size
        public void BuildParamSize(Parameter[] parameters, string strSizeVarName)
        {
            // size calculation
            MatchIndent();
            OutStream.Write(string.Format("int {0} = sizeof(UInt64)*2 ", strSizeVarName));

            if (parameters != null)
            {
                foreach (Parameter param in parameters)
                {
                    NewLine(); MatchIndent(1);
                    var typeInfo = SystemTypeInfo.GetParameterInfo(param);
                    if (typeInfo.IsString)
                    {
                        OutStream.Write("+ binWriter.StringEncoder.GetByteCount({0}) + 1 + 2", InParamName(param.Name));
                    }
                    else
                    {
                        if (param.IsArray)
                        {
                            OutStream.Write("+ Marshal.SizeOf({0})*({1}.Length) + sizeof(UInt16)", typeInfo.CSharpTypeName, InParamName(param.Name));
                        }
                        else
                        {
                            OutStream.Write("+ Marshal.SizeOf({0})", typeInfo.CSharpTypeName);
                        }
                    }
                }
            }

            OutStream.WriteLine(";");
        }
        public void Write(Span <byte> data, Meta meta)
        {
            if (OutStream == null || SendMode == TargetSendMode.None)
            {
                return;
            }

            meta.Out          = meta.Out ?? new MetaOut();
            meta.Out.SendMode = SendMode;
            switch (SendMode)
            {
            case TargetSendMode.None: break;

            case TargetSendMode.Voice: break;

            case TargetSendMode.Whisper:
                meta.Out.ChannelIds = setMeta.ChannelIds;
                meta.Out.ClientIds  = setMeta.ClientIds;
                break;

            case TargetSendMode.WhisperGroup:
                meta.Out.GroupWhisperTarget = setMeta.GroupWhisperTarget;
                meta.Out.GroupWhisperType   = setMeta.GroupWhisperType;
                meta.Out.TargetId           = setMeta.TargetId;
                break;

            default: throw new ArgumentOutOfRangeException(nameof(SendMode), SendMode, "SendMode not handled");
            }
            OutStream?.Write(data, meta);
        }
Beispiel #10
0
        private void PrintBody()
        {
            for (int rowcount = 0; rowcount < RawFile.Count; rowcount++)
            {
                string   line   = RawFile[rowcount];
                string[] fields = ParseClass.ParseLine(line, TrimFields, Delimiter, PreserveQuotes);

                PrintLineNumberField((StartSkipRows + rowcount + 1).ToString());
                PrintFieldCountField(fields.Length.ToString());

                for (int i = 0; i < MaxFieldCount; ++i)
                {
                    OutStream.Write("|");
                    if (i >= fields.Length)
                    {
                        PrintField(null, MaxFieldLengths[i], true);
                    }
                    else
                    {
                        PrintField(fields[i], MaxFieldLengths[i], true);
                    }
                }
                OutStream.Write("|" + System.Environment.NewLine);
            }
        }
Beispiel #11
0
        public void Write(Span <byte> data, Meta?meta)
        {
            if (OutStream is null || SendMode == TargetSendMode.None)
            {
                return;
            }

            meta ??= new Meta();
            meta.Out ??= new MetaOut();
            meta.Out.SendMode = SendMode;
            switch (SendMode)
            {
            case TargetSendMode.None: break;

            case TargetSendMode.Voice: break;

            case TargetSendMode.Whisper:
                meta.Out.ChannelIds = setMeta.ChannelIds;
                meta.Out.ClientIds  = setMeta.ClientIds;
                break;

            case TargetSendMode.WhisperGroup:
                meta.Out.GroupWhisperTarget = setMeta.GroupWhisperTarget;
                meta.Out.GroupWhisperType   = setMeta.GroupWhisperType;
                meta.Out.TargetId           = setMeta.TargetId;
                break;

            default: throw Tools.UnhandledDefault(SendMode);
            }
            OutStream?.Write(data, meta);
        }
        public override void Write(uint value)
        {
            fixed(byte *p = buffer)
            BigEndian.WriteInt32(p, (int)value);

            OutStream.Write(buffer, 0, 4);
        }
        public override void Write(double value)
        {
            fixed(byte *p = buffer)
            BigEndian.WriteInt64(p, Reinterpret.DoubleAsInt64(value));

            OutStream.Write(buffer, 0, 8);
        }
        public override void Write(float value)
        {
            fixed(byte *p = buffer)
            BigEndian.WriteDecimal(p, Reinterpret.FloatAsInt32(value));

            OutStream.Write(buffer, 0, 4);
        }
        public override void Write(decimal value)
        {
            fixed(byte *p = buffer)
            BigEndian.WriteDecimal(p, value);

            OutStream.Write(buffer, 0, 16);
        }
Beispiel #16
0
        public override void Write(ushort value)
        {
            buffer_[0] = (byte)(value >> 8);
            buffer_[1] = (byte)value;

            OutStream.Write(buffer_, 0, 2);
        }
Beispiel #17
0
        public void WriteShortString(string value)
        {
            var byteCount = _encoding.GetByteCount(value);

            if (byteCount is > Int16.MaxValue or < 0)
            {
                throw Error.WriteInvalidStringLength(byteCount);
            }
            Write((short)byteCount);
            if (_largeByteBuffer is null)
            {
                _largeByteBuffer = new byte[256];
                _maxChars        = _largeByteBuffer.Length / _encoding.GetMaxByteCount(1);
            }
            if (byteCount <= _largeByteBuffer.Length)
            {
                _ = _encoding.GetBytes(value, _largeByteBuffer);
                OutStream.Write(_largeByteBuffer, 0, byteCount);
                return;
            }
            var num  = value.Length;
            var num2 = 0;
            ReadOnlySpan <char> span = value;

            if (_encoding.GetType() == typeof(UTF8Encoding))
            {
                while (num > 0)
                {
                    _encoder.Convert(span[num2..], _largeByteBuffer, num <= _maxChars, out var charsUsed, out var bytesUsed, out _);
        public void Signal <T>(T payload)
        {
            ThrowIfDisposed();

            var hydrator = settings.Hydrator;

            using (Stream dehydreated = hydrator.Dehydrate(payload))
            {
                byte[] buffer = new byte[0x100];
                int    size   = 0;
                do
                {
                    size = ReadBytes(buffer, dehydreated);

                    var header = HeaderPacktToByteArray(new HeaderPacket
                    {
                        Final = size < buffer.Length,
                        Size  = size
                    });

                    OutStream.Write(header, 0, header.Length);
                    if (size > 0)
                    {
                        OutStream.Write(buffer, 0, size);
                    }
                } while (size != 0);
            }

            OutStream.Flush();

            if (settings.WaitForDrain)
            {
                OutStream.WaitForPipeDrain();
            }
        }
Beispiel #19
0
 private void PrintLineNumberField(string s)
 {
     if (PrintLineNumber)
     {
         OutStream.Write('|');
         PrintField(s, LengthOfMaxLineNumber, true);
     }
 }
 /// <summary>
 /// Writes an unsigned 32-bit integer in network byte order.
 /// </summary>
 /// <param name="value">value to write</param>
 public override void Write(uint value)
 {
     buffer[0] = (byte)(value >> 0x18);
     buffer[1] = (byte)(value >> 0x10);
     buffer[2] = (byte)(value >> 0x08);
     buffer[3] = (byte)value;
     OutStream.Write(buffer, 0, 4);
 }
Beispiel #21
0
 private void PrintFieldCountField(string s)
 {
     if (PrintFieldCount)
     {
         OutStream.Write('|');
         PrintField(s, LengthOfMaxFieldCount, true);
     }
 }
Beispiel #22
0
        public override void Write(uint value)
        {
            buffer_[0] = (byte)(value >> 24);
            buffer_[1] = (byte)(value >> 16);
            buffer_[2] = (byte)(value >> 8);
            buffer_[3] = (byte)value;

            OutStream.Write(buffer_, 0, 4);
        }
        /// <summary>
        /// Writes a single precision (32-bit) floating point number in network byte order.
        /// </summary>
        /// <param name="value">value to write</param>
        public override unsafe void Write(float value)
        {
            uint num = *((uint *)&value);

            buffer[0] = (byte)(num >> 0x18);
            buffer[1] = (byte)(num >> 0x10);
            buffer[2] = (byte)(num >> 0x08);
            buffer[3] = (byte)(num >> 0x00);
            OutStream.Write(buffer, 0, 4);
        }
Beispiel #24
0
        private void PacketEvent(ConnectionContext ctx, ref Packet <S2C> packet)
        {
            switch (packet.PacketType)
            {
            case PacketType.Command:
            case PacketType.CommandLow:
                var data = packet.Data;
                if (Log.IsDebugEnabled)
                {
                    Log.Debug("[I] {0}", Tools.Utf8Encoder.GetString(packet.Data));
                }
                _ = scheduler.Invoke(() =>
                {
                    if (ctx != context)
                    {
                        Log.Debug("Stray packet from old packethandler");
                    }

                    var result = msgProc.PushMessage(data);
                    if (result != null)
                    {
                        InvokeEvent(result.Value);
                    }
                });
                break;

            case PacketType.Voice:
            case PacketType.VoiceWhisper:
                OutStream?.Write(packet.Data, new Meta
                {
                    In = new MetaIn
                    {
                        Whisper = packet.PacketType == PacketType.VoiceWhisper
                    }
                });
                break;

            case PacketType.Init1:
                // Init error
                if (packet.Data.Length == 5 && packet.Data[0] == 1)
                {
                    var errorNum = BinaryPrimitives.ReadUInt32LittleEndian(packet.Data.AsSpan(1));
                    if (Enum.IsDefined(typeof(TsErrorCode), errorNum))
                    {
                        Log.Info("Got init error: {0}", (TsErrorCode)errorNum);
                    }
                    else
                    {
                        Log.Warn("Got undefined init error: {0}", errorNum);
                    }
                    _ = scheduler.Invoke(() => ChangeState(ctx, TsClientStatus.Disconnected));
                }
                break;
            }
        }
Beispiel #25
0
        public override void Write(float value)
        {
            byte[] valueBytes = BitConverter.GetBytes(value);

            _buffer[0] = valueBytes[3];
            _buffer[1] = valueBytes[2];
            _buffer[2] = valueBytes[1];
            _buffer[3] = valueBytes[0];

            OutStream.Write(_buffer, 0, 4);
        }
Beispiel #26
0
        public override unsafe void Write(float value)
        {
            uint tmpValue = *(uint *)&value;

            buffer_[0] = (byte)(tmpValue >> 24);
            buffer_[1] = (byte)(tmpValue >> 16);
            buffer_[2] = (byte)(tmpValue >> 8);
            buffer_[3] = (byte)tmpValue;

            OutStream.Write(buffer_, 0, 4);
        }
Beispiel #27
0
        public override void Write(decimal value)
        {
            var span = _buffer.AsSpan();
            var num  = Decimal.GetBits(value);

            BinaryPrimitives.WriteInt32BigEndian(span.Slice(0, 4), num[3]);
            BinaryPrimitives.WriteInt32BigEndian(span.Slice(4, 4), num[2]);
            BinaryPrimitives.WriteInt32BigEndian(span.Slice(8, 4), num[1]);
            BinaryPrimitives.WriteInt32BigEndian(span.Slice(12, 4), num[0]);
            OutStream.Write(_buffer, 0, 16);
        }
 /// <summary>
 /// Writes an unsigned 64-bit integer in network byte order.
 /// </summary>
 /// <param name="value">value to write</param>
 public override void Write(ulong value)
 {
     buffer[0] = (byte)(value >> 0x38);
     buffer[1] = (byte)(value >> 0x30);
     buffer[2] = (byte)(value >> 0x28);
     buffer[3] = (byte)(value >> 0x20);
     buffer[4] = (byte)(value >> 0x18);
     buffer[5] = (byte)(value >> 0x10);
     buffer[6] = (byte)(value >> 0x08);
     buffer[7] = (byte)(value >> 0x00);
     OutStream.Write(buffer, 0, 8);
 }
Beispiel #29
0
        public override void Write(ulong value)
        {
            buffer_[0] = (byte)(value >> 56);
            buffer_[1] = (byte)(value >> 48);
            buffer_[2] = (byte)(value >> 40);
            buffer_[3] = (byte)(value >> 32);
            buffer_[4] = (byte)(value >> 24);
            buffer_[5] = (byte)(value >> 16);
            buffer_[6] = (byte)(value >> 8);
            buffer_[7] = (byte)value;

            OutStream.Write(buffer_, 0, 8);
        }
Beispiel #30
0
        private void PacketEvent(ConnectionContext ctx, ref Packet <S2C> packet)
        {
            lock (statusLock)
            {
                if (ctx.WasExit)
                {
                    return;
                }

                switch (packet.PacketType)
                {
                case PacketType.Command:
                case PacketType.CommandLow:
                    Log.ConditionalDebug("[I] {0}", Tools.Utf8Encoder.GetString(packet.Data));
                    var result = msgProc.PushMessage(packet.Data);
                    if (result.HasValue)
                    {
                        dispatcher.Invoke(result.Value);
                    }
                    break;

                case PacketType.Voice:
                case PacketType.VoiceWhisper:
                    OutStream?.Write(packet.Data, new Meta
                    {
                        In = new MetaIn
                        {
                            Whisper = packet.PacketType == PacketType.VoiceWhisper
                        }
                    });
                    break;

                case PacketType.Init1:
                    // Init error
                    if (packet.Data.Length == 5 && packet.Data[0] == 1)
                    {
                        var errorNum = BinaryPrimitives.ReadUInt32LittleEndian(packet.Data.AsSpan(1));
                        if (Enum.IsDefined(typeof(TsErrorCode), errorNum))
                        {
                            Log.Info("Got init error: {0}", (TsErrorCode)errorNum);
                        }
                        else
                        {
                            Log.Warn("Got undefined init error: {0}", errorNum);
                        }
                        DisconnectInternal(ctx, setStatus: TsClientStatus.Disconnected);
                    }
                    break;
                }
            }
        }
Beispiel #31
0
        /// <summary>
        /// Writes a packet to a stream.
        /// </summary>
        public static void Write(Packet Packet, OutStream Stream)
        {
            // Build flags and header
            PacketFlags flags = PacketFlags.Empty;
            if (Packet.AcknowledgementNumber.HasValue)
                flags |= PacketFlags.Acknowledgement;
            if (Packet.RoundTripTime.HasValue)
                flags |= PacketFlags.RoundTripTime;
            if (Packet.ChunkData != null)
            {
                flags |= PacketFlags.Chunk;
                if (Packet.ChunkInitial)
                    flags |= PacketFlags.ChunkInitial;
                if (Packet.ChunkFinal)
                    flags |= PacketFlags.ChunkFinal;
            }
            if (Packet.PingRequest)
                flags |= PacketFlags.PingRequest;
            if (Packet.PingResponse)
                flags |= PacketFlags.PingResponse;
            if (Packet.Disconnect)
                flags |= PacketFlags.Disconnect;
            Stream.WriteByte((byte)flags);
            Stream.WriteInt(Packet.SequenceNumber);

            // Additional information
            int ack;
            if (Packet.AcknowledgementNumber.TryGetValue(out ack))
                Stream.WriteInt(ack);

            double rtt;
            if (Packet.RoundTripTime.TryGetValue(out rtt))
                Stream.WriteDouble(rtt);

            // Chunk
            if (Packet.ChunkData != null)
                Stream.Write(Packet.ChunkData, 0, Packet.ChunkData.Length);
        }