/*
 * Copyright ©2026 Soham Pardeshi. All rights reserved.
 * Permission is hereby granted to students registered for University of
 * Washington CSE 333 for use solely during Summer Quarter 2026 for
 * purposes of the course. No other use, copying, distribution, or
 * modification is permitted without prior written consent. Copyrights
 * for third-party components of this work must be honored. Instructors
 * interested in reusing these course materials should contact the author.
 */

#include <errno.h>    // errno, EINTR
#include <stdlib.h>   // EXIT_SUCCESS
#include <string.h>   // strlen
#include <unistd.h>   // write, STDOUT_FILENO

// WriteAll: write exactly n bytes from buf to fd.
//
// The mirror of ReadAll. write() can also accept fewer bytes than you
// hand it, so we loop and advance by what actually got written, retrying
// on EINTR. There is no EOF case: writing never hits end-of-file, so the
// loop is a touch simpler than read's. Returns the number of bytes written.
int WriteAll(int fd, const char* buf, int n) {
  int bytes_left = n;
  int result;
  while (bytes_left > 0) {
    result = write(fd, buf + (n - bytes_left), bytes_left);
    if (result == -1) {
      if (errno != EINTR) {
        break;          // a real error
      }
      continue;         // EINTR: just retry
    }
    bytes_left -= result;
  }
  return n - bytes_left;
}

int main(int argc, char** argv) {
  const char* msg = "hello from WriteAll\n";
  WriteAll(STDOUT_FILENO, msg, strlen(msg));
  return EXIT_SUCCESS;
}