From 250ce08712cabb52d7136bb4dfd3e0db6a83782f Mon Sep 17 00:00:00 2001 From: porkybrain Date: Wed, 15 Apr 2015 17:07:40 +0200 Subject: [PATCH] Changed CircBuffer to take its size as a template parameters. This results in smaller code size and less ram usage because the optimizer knows the size at compile time and it does not need to be stored in ram. It should also be faster because there is no indirection to the heap. I have not tested this code! --- libraries/USBDevice/USBSerial/CircBuffer.h | 21 +++++---------------- libraries/USBDevice/USBSerial/USBSerial.h | 4 ++-- 2 files changed, 7 insertions(+), 18 deletions(-) diff --git a/libraries/USBDevice/USBSerial/CircBuffer.h b/libraries/USBDevice/USBSerial/CircBuffer.h index 78d5eecc6c..b784a72019 100644 --- a/libraries/USBDevice/USBSerial/CircBuffer.h +++ b/libraries/USBDevice/USBSerial/CircBuffer.h @@ -19,20 +19,9 @@ #ifndef CIRCBUFFER_H #define CIRCBUFFER_H -template +template class CircBuffer { public: - CircBuffer(int length) { - write = 0; - read = 0; - size = length + 1; - buf = (T *)malloc(size * sizeof(T)); - }; - - ~CircBuffer() { - free(buf); - } - bool isFull() { return ((write + 1) % size == read); }; @@ -64,10 +53,10 @@ public: }; private: - volatile uint16_t write; - volatile uint16_t read; - uint16_t size; - T * buf; + volatile uint16_t write{0}; //in case older compilers are targeted this should be done in a constructor + volatile uint16_t read{0}; + static constexpr int size{Size+1}; + T buf[Size]; }; #endif diff --git a/libraries/USBDevice/USBSerial/USBSerial.h b/libraries/USBDevice/USBSerial/USBSerial.h index e83aea6b18..164cf9bc7d 100644 --- a/libraries/USBDevice/USBSerial/USBSerial.h +++ b/libraries/USBDevice/USBSerial/USBSerial.h @@ -56,7 +56,7 @@ public: * @param connect_blocking define if the connection must be blocked if USB not plugged in * */ - USBSerial(uint16_t vendor_id = 0x1f00, uint16_t product_id = 0x2012, uint16_t product_release = 0x0001, bool connect_blocking = true): USBCDC(vendor_id, product_id, product_release, connect_blocking), buf(128){ + USBSerial(uint16_t vendor_id = 0x1f00, uint16_t product_id = 0x2012, uint16_t product_release = 0x0001, bool connect_blocking = true): USBCDC(vendor_id, product_id, product_release, connect_blocking){ settingsChangedCallback = 0; }; @@ -154,7 +154,7 @@ protected: private: FunctionPointer rx; - CircBuffer buf; + CircBuffer buf; void (*settingsChangedCallback)(int baud, int bits, int parity, int stop); };