From bfa20af8555719344db9b0a478445f4d218e5fec Mon Sep 17 00:00:00 2001
From: sheinz <shein@bk.ru>
Date: Thu, 14 Jul 2016 15:44:02 +0300
Subject: [PATCH] Fix branch merging.

Changes in esp_spiffs.c recovered.
---
 extras/spiffs/esp_spiffs.c | 68 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 68 insertions(+)

diff --git a/extras/spiffs/esp_spiffs.c b/extras/spiffs/esp_spiffs.c
index d6ec7d6..4b5ef77 100644
--- a/extras/spiffs/esp_spiffs.c
+++ b/extras/spiffs/esp_spiffs.c
@@ -9,6 +9,8 @@
 #include "spiffs.h"
 #include <espressif/spi_flash.h>
 #include <stdbool.h>
+#include <esp/uart.h>
+#include <fcntl.h>
 
 spiffs fs;
 
@@ -185,3 +187,69 @@ void esp_spiffs_unmount()
     fds_buf = 0;
     cache_buf = 0;
 }
+
+#define FD_OFFSET 3
+
+// This implementation replaces implementation in core/newlib_syscals.c
+long _write_r(struct _reent *r, int fd, const char *ptr, int len )
+{
+    if(fd != r->_stdout->_file) {
+        long ret = SPIFFS_write(&fs, (spiffs_file)(fd - FD_OFFSET), 
+                (char*)ptr, len);
+        return ret;
+    }
+    for(int i = 0; i < len; i++) {
+        /* Auto convert CR to CRLF, ignore other LFs (compatible with Espressif SDK behaviour) */
+        if(ptr[i] == '\r')
+            continue;
+        if(ptr[i] == '\n')
+            uart_putc(0, '\r');
+        uart_putc(0, ptr[i]);
+    }
+    return len;
+}
+
+// This implementation replaces implementation in core/newlib_syscals.c
+long _read_r( struct _reent *r, int fd, char *ptr, int len )
+{
+    int ch, i;
+
+    if(fd != r->_stdin->_file) {
+        long ret = SPIFFS_read(&fs, (spiffs_file)(fd - FD_OFFSET), ptr, len);
+        return ret;
+    }
+    uart_rxfifo_wait(0, 1);
+    for(i = 0; i < len; i++) {
+        ch = uart_getc_nowait(0);
+        if (ch < 0) break;
+        ptr[i] = ch;
+    }
+    return i;
+}
+
+int _open_r(struct _reent *r, const char *pathname, int flags, int mode)
+{
+    uint32_t spiffs_flags = SPIFFS_RDONLY;
+
+    if (flags & O_CREAT)    spiffs_flags |= SPIFFS_CREAT;
+    if (flags & O_APPEND)   spiffs_flags |= SPIFFS_APPEND;
+    if (flags & O_TRUNC)    spiffs_flags |= SPIFFS_TRUNC;
+    if (flags & O_RDONLY)   spiffs_flags |= SPIFFS_RDONLY;
+    if (flags & O_WRONLY)   spiffs_flags |= SPIFFS_WRONLY;
+
+    int ret = SPIFFS_open(&fs, pathname, spiffs_flags, mode);
+    if (ret > 0) {
+        return ret + FD_OFFSET;
+    }
+    return ret;
+}
+
+int _close_r(struct _reent *r, int fd)
+{
+    return SPIFFS_close(&fs, (spiffs_file)(fd - FD_OFFSET));
+}
+
+int _unlink_r(struct _reent *r, const char *path)
+{
+    return SPIFFS_remove(&fs, path);
+}