Skip to content

Commit 07cd804

Browse files
committed
Add Span examples
1 parent 046b596 commit 07cd804

File tree

4 files changed

+71
-0
lines changed

4 files changed

+71
-0
lines changed

APIs_Platform/Span_c/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
## Span example
2+
3+
The example shows how to use Span class to operate on the string buffer.
4+
5+
**Note:** C example code

APIs_Platform/Span_c/main.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#include "mbed.h"
2+
#include "platform/Span.h"
3+
4+
template<typename T>
5+
void split(const T **in_ptr, ptrdiff_t *in_size, const T **token_ptr, ptrdiff_t *token_size, const T &separator)
6+
{
7+
const ptrdiff_t out_of_range = *in_size;
8+
9+
ptrdiff_t start;
10+
for (start = 0; start != out_of_range && (*in_ptr)[start] == separator; ++start) { }
11+
12+
ptrdiff_t last;
13+
for (last = start; last != out_of_range && (*in_ptr)[last] != separator; ++last) { }
14+
15+
*token_ptr = *in_ptr + start;
16+
*token_size = last - start;
17+
18+
*in_size = *in_size - last;
19+
*in_ptr = *in_ptr + last;
20+
}
21+
22+
int main()
23+
{
24+
const char str[] = "Hello World! Hello mbed-os!";
25+
const char *buffer_ptr = str;
26+
ptrdiff_t buffer_size = sizeof(str);
27+
while (buffer_size) {
28+
const char *token_ptr = NULL;
29+
ptrdiff_t token_size = 0;
30+
split(&buffer_ptr, &buffer_size, &token_ptr, &token_size, ' ');
31+
printf("token: %.*s\r\n", token_size, token_ptr);
32+
}
33+
}

APIs_Platform/Span_cpp/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
## Span example
2+
3+
The example shows how to use Span class to operate on the string buffer.
4+
5+
**Note:** C++ example code

APIs_Platform/Span_cpp/main.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include "mbed.h"
2+
#include "platform/Span.h"
3+
4+
template<typename T>
5+
Span<const T> split(Span<const T> &range, const T &separator)
6+
{
7+
const ptrdiff_t out_of_range = range.size();
8+
9+
ptrdiff_t start;
10+
for (start = 0; start != out_of_range && range[start] == separator; ++start) { }
11+
12+
ptrdiff_t last;
13+
for (last = start; last != out_of_range && range[last] != separator; ++last) { }
14+
15+
Span<const T> result = range.subspan(start, last - start);
16+
range = range.subspan(last);
17+
return result;
18+
}
19+
20+
21+
int main()
22+
{
23+
Span<const char> buffer("Hello World! Hello mbed-os!");
24+
while (buffer.empty() == false) {
25+
Span<const char> token = split(buffer, ' ');
26+
printf("token: %.*s\r\n", token.size(), token.data());
27+
}
28+
}

0 commit comments

Comments
 (0)