#import "Shared_Memory_Channel"; #import "Basic"; // Settings that both 'read' and 'write' use: #load "common.jai"; CHANNEL_DATA_BYTES :: 65536; // Note: The checksum is here just to make sure there isn't a bug, not because // we are worried about bits being corrupted. main :: () { success, channel := reader_create_channel("Cowabunga!", CHANNEL_DATA_BYTES); if !success { log_error("Exiting due to channel creation failure.\n"); return; } defer reader_release_channel(*channel); write_string("Started reading.\n"); messages_read := 0; while 1 { message_success, fatal_error, message := reader_poll_for_message(*channel); // If message_success == false, it could mean there's just no message ready yet. if message_success { // We know, due to our user-level protocol, messages must be at least 1 byte. // If we get a 0-byte message, that is bad! If we get a 1-byte message, and // it is not Protocol_Tag.DONE, that is bad! I reordered the checks here // to make it a bit simpler: bytes := message.user_read_bytes; if bytes >= HEADER_SIZE { command := message.user_read_pointer[0]; if command != cast(u8) Protocol_Tag.MESSAGE { log_error("Got an invalid command on a data message: %\n", command); return; } stored_checksum := message.user_read_pointer[1]; data_bytes := message.user_read_bytes - HEADER_SIZE; my_checksum: u8; for 0..data_bytes-1 { my_checksum ^= message.user_read_pointer[it + HEADER_SIZE]; } if my_checksum != stored_checksum { log_error("Checksum mismatch in message #%: Wanted %, got %. Quitting.\n", messages_read+1, stored_checksum, my_checksum); return; } } else if bytes == 1 { command := message.user_read_pointer[0]; if command == cast(u8) Protocol_Tag.DONE { log("Received DONE; breaking from the loop.\n"); break; } } else { log_error("Got a message that is too short! Quitting.\n"); return; } reader_done_with_message(*message); messages_read += 1; } if fatal_error { print("FATAL error!\n"); return; } else if !message_success { sleep_milliseconds(1); } } log("Reader has successfully received % messages!\n", messages_read); assert(messages_read == NUMBER_OF_MESSAGES); }