Merge pull request #282 from abailly/network-binary

provide building blocks for binary network I/O
This commit is contained in:
Edwin Brady 2020-04-21 10:45:52 +01:00 committed by GitHub
commit 5ea11cf0f5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 39 additions and 0 deletions

View File

@ -23,7 +23,18 @@ data SockaddrPtr = SAPtr AnyPtr
-- ---------------------------------------------------------- [ Socket Utilies ]
||| Put a value in a buffer
export
sock_poke : BufPtr -> Int -> Int -> IO ()
sock_poke (BPtr ptr) offset val = cCall () "idrnet_poke" [ptr, offset, val]
||| Take a value from a buffer
export
sock_peek : BufPtr -> Int -> IO Int
sock_peek (BPtr ptr) offset = cCall Int "idrnet_peek" [ptr, offset]
||| Frees a given pointer
export
sock_free : BufPtr -> IO ()
sock_free (BPtr ptr) = cCall () "idrnet_free" [ptr]
@ -34,6 +45,7 @@ sockaddr_free (SAPtr ptr) = cCall () "idrnet_free" [ptr]
||| Allocates an amount of memory given by the ByteLength parameter.
|||
||| Used to allocate a mutable pointer to be given to the Recv functions.
export
sock_alloc : ByteLength -> IO BufPtr
sock_alloc bl = map BPtr $ cCall AnyPtr "idrnet_malloc" [bl]

View File

@ -56,6 +56,16 @@ void idrnet_free(void* ptr) {
free(ptr);
}
unsigned int idrnet_peek(void *ptr, unsigned int offset) {
unsigned char *buf_c = (unsigned char*) ptr;
return (unsigned int) buf_c[offset];
}
void idrnet_poke(void *ptr, unsigned int offset, char val) {
char *buf_c = (char*)ptr;
buf_c[offset] = val;
}
int idrnet_socket(int domain, int type, int protocol) {
#ifdef _WIN32

View File

@ -31,6 +31,8 @@ typedef struct idrnet_recvfrom_result {
// Memory management functions
void* idrnet_malloc(int size);
void idrnet_free(void* ptr);
unsigned int idrnet_peek(void *ptr, unsigned int offset);
void idrnet_poke(void *ptr, unsigned int offset, char val);
// Gets value of errno
int idrnet_errno();

View File

@ -31,10 +31,25 @@ void test_sockaddr_port_returns_explicitly_assigned_port() {
close(sock);
}
void test_peek_and_poke_buffer() {
void *buf = idrnet_malloc(100);
assert(buf > 0);
for (int i = 0; i < 100; i++) {
idrnet_poke(buf,i,7*i);
}
for(int i = 0; i < 100; i++) {
assert (idrnet_peek(buf,i) == (0xff & 7*i));
}
idrnet_free(buf);
}
int main(int argc, char**argv) {
test_sockaddr_port_returns_explicitly_assigned_port();
test_sockaddr_port_returns_random_port_when_bind_port_is_0();
test_peek_and_poke_buffer();
printf("network library tests SUCCESS\n");
return 0;