LineBuffer.h
Go to the documentation of this file.
1 /****
2  * Sming Framework Project - Open Source framework for high efficiency native ESP8266 development.
3  * Created 2015 by Skurydin Alexey
4  * http://github.com/SmingHub/Sming
5  * All files of the Sming Core are provided under the LGPL v3 license.
6  *
7  * LineBuffer.h - support for buffering/editing a line of text
8  *
9  * author mikee47 <mike@sillyhouse.net> Feb 2019
10  *
11  ****/
12 
13 #pragma once
14 
15 #include <user_config.h>
16 
21 template <uint16_t BUFSIZE> class LineBuffer
22 {
23 public:
28  char addChar(char c);
29 
33  void clear()
34  {
35  length = 0;
36  }
37 
41  char* getBuffer()
42  {
43  return buffer;
44  }
45 
49  unsigned getLength() const
50  {
51  return length;
52  }
53 
59  bool startsWith(const char* text) const;
60 
66  bool contains(const char* text) const;
67 
72  bool backspace();
73 
74 private:
75  char buffer[BUFSIZE] = {'\0'};
76  uint16_t length = 0;
77 };
78 
79 template <uint16_t BUFSIZE> char LineBuffer<BUFSIZE>::addChar(char c)
80 {
81  if(c == '\n' || c == '\r') {
82  return '\n';
83  }
84 
85  if(c >= 0x20 && c < 0x7f && length < (BUFSIZE - 1)) {
86  buffer[length++] = c;
87  buffer[length] = '\0';
88  return c;
89  }
90 
91  return '\0';
92 }
93 
94 template <uint16_t BUFSIZE> bool LineBuffer<BUFSIZE>::backspace()
95 {
96  if(length == 0) {
97  return false;
98  } else {
99  --length;
100  buffer[length] = '\0';
101  return true;
102  }
103 }
104 
105 template <uint16_t BUFSIZE> bool LineBuffer<BUFSIZE>::startsWith(const char* text) const
106 {
107  auto len = strlen(text);
108  return memcmp(buffer, text, len) == 0;
109 }
110 
111 template <uint16_t BUFSIZE> bool LineBuffer<BUFSIZE>::contains(const char* text) const
112 {
113  return strstr(buffer, text) != nullptr;
114 }
bool startsWith(const char *text) const
Check for matching text at start of line, case-sensitive.
Definition: LineBuffer.h:105
bool backspace()
Remove last character from buffer.
Definition: LineBuffer.h:94
bool contains(const char *text) const
Check for matching text anywhere in line, case-sensitive.
Definition: LineBuffer.h:111
Class to enable buffering of a single line of text, with simple editing.
Definition: LineBuffer.h:21
char * getBuffer()
Get the text, nul-terminated.
Definition: LineBuffer.h:41
void clear()
Clear contents of buffer.
Definition: LineBuffer.h:33
char addChar(char c)
Add a character to the buffer.
Definition: LineBuffer.h:79
unsigned getLength() const
Get number of characters in the text line.
Definition: LineBuffer.h:49