}
protected int fwrite(ByteList buffer) {
int n, r, l, offset = 0;
boolean eagain = false;
Stream writeStream = openFile.getWriteStream();
int len = buffer.length();
if ((n = len) <= 0) return n;
try {
if (openFile.isSync()) {
openFile.fflush(writeStream);
// TODO: why is this guarded?
// if (!rb_thread_fd_writable(fileno(f))) {
// rb_io_check_closed(fptr);
// }
while(offset<len) {
l = n;
// TODO: Something about pipe buffer length here
r = writeStream.getDescriptor().write(buffer,offset,l);
if(r == len) {
return len; //Everything written
}
if (0 <= r) {
offset += r;
n -= r;
eagain = true;
}
if(eagain && waitWritable(writeStream.getDescriptor())) {
openFile.checkClosed(getRuntime());
if(offset >= buffer.length()) {
return -1;
}
eagain = false;
} else {
return -1;
}
}
// TODO: all this stuff...some pipe logic, some async thread stuff
// retry:
// l = n;
// if (PIPE_BUF < l &&
// !rb_thread_critical &&
// !rb_thread_alone() &&
// wsplit_p(fptr)) {
// l = PIPE_BUF;
// }
// TRAP_BEG;
// r = write(fileno(f), RSTRING(str)->ptr+offset, l);
// TRAP_END;
// if (r == n) return len;
// if (0 <= r) {
// offset += r;
// n -= r;
// errno = EAGAIN;
// }
// if (rb_io_wait_writable(fileno(f))) {
// rb_io_check_closed(fptr);
// if (offset < RSTRING(str)->len)
// goto retry;
// }
// return -1L;
}
// TODO: handle errors in buffered write by retrying until finished or file is closed
return writeStream.fwrite(buffer);
// while (errno = 0, offset += (r = fwrite(RSTRING(str)->ptr+offset, 1, n, f)), (n -= r) > 0) {
// if (ferror(f)
// ) {
// if (rb_io_wait_writable(fileno(f))) {
// rb_io_check_closed(fptr);