1 // =================================
 2 // Copyright (c) 2024 Seppo Laakko
 3 // Distributed under the MIT license
 4 // =================================
 5 
 6 using System;
 7 using System.IO;
 8 
 9 namespace System.Net.Sockets
10 {
11     public class NetworkStream : Stream
12     {
13         public NetworkStream(TcpSocket&& socket_) : socket(socket_)
14         {
15         }
16         [nodiscard]
17         public override Result<int> ReadByte()
18         {
19             byte buf;
20             auto readResult = Read(&buf1);
21             if (readResult.Error())
22             {
23                 return Result<int>(ErrorId(readResult.GetErrorId()));
24             }
25             long bytesRead = readResult.Value();
26             if (bytesRead == 0)
27             {
28                 return Result<int>(-1);
29             }
30             else
31             {
32                 return Result<int>(buf);
33             }
34         }
35         [nodiscard]
36         public override Result<long> Read(byte* buflong count)
37         {
38             auto receiveResult = socket.Receive(bufcast<int>(count));
39             if (receiveResult.Error())
40             {
41                 return Result<long>(ErrorId(receiveResult.GetErrorId()));
42             }
43             int bytesReceived = receiveResult.Value();
44             return Result<long>(cast<long>(bytesReceived));
45         }
46         [nodiscard]
47         public override Result<bool> Write(byte x)
48         {
49             return Write(&x1);
50         }
51         [nodiscard]
52         public override Result<bool> Write(byte* buflong count)
53         {
54             return socket.SendAll(bufcast<int>(count));
55         }
56         public TcpSocket& Socket()
57         {
58             return socket;
59         }
60         private TcpSocket socket;
61     }
62 }