Skip to content

Commit 2134a33

Browse files
committed
Add implementation of strndup function and test for it
1 parent 712bc90 commit 2134a33

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

AUTHORS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,4 @@ under the licensing terms detailed in LICENSE.
2222
* Brian Anderson <[email protected]>
2323
* Jon Bardin <[email protected]>
2424
* Jukka Jyl�nki <[email protected]>
25+
* Aleksander Guryanov <[email protected]>

src/library.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4199,6 +4199,20 @@ LibraryManager.library = {
41994199
return newStr;
42004200
},
42014201

4202+
strndup__deps: ['strdup'],
4203+
strndup: function(ptr, size) {
4204+
var len = String_len(ptr);
4205+
4206+
if (size <= 0 || size >= len) {
4207+
return _strdup(ptr);
4208+
}
4209+
4210+
var newStr = _malloc(0 + 1);
4211+
{{{ makeCopyValues('newStr', 'ptr', 'size', 'null', null, 1) }}};
4212+
{{{ makeSetValue('newStr', 'size', '0', 'i8') }}};
4213+
return newStr;
4214+
},
4215+
42024216
strpbrk: function(ptr1, ptr2) {
42034217
var searchSet = Runtime.set.apply(null, String_copy(ptr2));
42044218
while ({{{ makeGetValue('ptr1', 0, 'i8') }}}) {

tests/runner.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1393,6 +1393,40 @@ def test_strings(self):
13931393
'''
13941394
self.do_run(src, '4:10,177,543,def\n4\nwowie\ntoo\n76\n5\n(null)\n/* a comment */\n// another\ntest\n', ['wowie', 'too', '74'])
13951395

1396+
def test_strndup(self):
1397+
src = '''
1398+
//---------------
1399+
//- http://pubs.opengroup.org/onlinepubs/9699919799/functions/strndup.html
1400+
//---------------
1401+
1402+
#include <stdio.h>
1403+
#include <stdlib.h>
1404+
#include <string.h>
1405+
1406+
int main(int argc, char **argv) {
1407+
const char* source = "strndup - duplicate a specific number of bytes from a string";
1408+
1409+
char* strdup_val = strndup(source, 7);
1410+
printf("%s\\n", strdup_val);
1411+
free(strdup_val);
1412+
1413+
strdup_val = strndup(source, 1000);
1414+
printf("%s\\n", strdup_val);
1415+
free(strdup_val);
1416+
1417+
strdup_val = strndup(source, 60);
1418+
printf("%s\\n", strdup_val);
1419+
free(strdup_val);
1420+
1421+
strdup_val = strndup(source, 19);
1422+
printf("%s\\n", strdup_val);
1423+
free(strdup_val);
1424+
1425+
return 0;
1426+
}
1427+
'''
1428+
self.do_run(src, 'strndup\nstrndup - duplicate a specific number of bytes from a string\nstrndup - duplicate a specific number of bytes from a string\nstrndup - duplicate\n')
1429+
13961430
def test_errar(self):
13971431
src = r'''
13981432
#include <stdio.h>

0 commit comments

Comments
 (0)