Coverage Report

Created: 2025-08-26 06:43

/src/clib/deps/substr/substr.c
Line
Count
Source (jump to first uncovered line)
1
2
//
3
// substr.c
4
//
5
// Copyright (c) 2013 Stephen Mathieson
6
// MIT licensed
7
//
8
9
#include <stdlib.h>
10
#include <string.h>
11
#include "strdup/strdup.h"
12
#include "substr.h"
13
14
/*
15
 * Get a substring of `str` from `start` to `end`
16
 */
17
18
char *
19
2.47k
substr(const char *str, int start, int end) {
20
2.47k
  if (0 > start) return NULL;
21
2.47k
  int len = strlen(str);
22
  // -1 == length of string
23
2.47k
  if (-1 == end) end = len;
24
2.47k
  if (end <= start) return NULL;
25
1.57k
  int diff = end - start;
26
1.57k
  if (len == diff) return strdup(str);
27
1.57k
  if (len < start) return NULL;
28
1.57k
  if (len + 1 < end) return NULL;
29
30
1.57k
  char *res = malloc(sizeof(char) * diff + 1);
31
1.57k
  if (NULL == res) return NULL;
32
1.57k
  memset(res, '\0', diff + 1);
33
1.57k
  strncpy(res, str + start, diff);
34
1.57k
  return res;
35
1.57k
}