Last active
August 29, 2015 14:08
-
-
Save adamnemecek/2503eab6c49f7210ef81 to your computer and use it in GitHub Desktop.
template.concat.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include <wchar.h> | |
#ifndef uint_t | |
typedef unsigned uint_t; | |
#endif | |
typedef char CHAR; | |
typedef wchar_t WCHAR; | |
template <typename T> | |
uint_t StringLength(const T *str); | |
template <> | |
uint_t StringLength(const CHAR *str) | |
{ | |
return str != nullptr ? (uint_t)strlen(str) : 0; | |
} | |
template <> | |
uint_t StringLength(const WCHAR *str) | |
{ | |
return str != nullptr ? (uint_t)wcslen(str) : 0; | |
} | |
template <typename T> | |
uint_t StringsLengths(uint_t *cch, const T *head) | |
{ | |
return cch[0] = StringLength(head); | |
} | |
template <typename T, typename ...Ts> | |
uint_t StringsLengths(uint_t *cch, const T *head, const Ts *...tail) | |
{ | |
return StringsLengths(&cch[0], head) + StringsLengths(&cch[1], tail...); | |
} | |
template <typename T> | |
void CopyStrings(T *buffer, uint_t *cch, const T *head) | |
{ | |
memcpy(buffer, head, cch[0] * sizeof(T)); | |
} | |
template <typename T, typename ...Ts> | |
void CopyStrings(T *buffer, uint_t *cch, const T *head, const Ts *...tail) | |
{ | |
CopyStrings(buffer, &cch[0], head); | |
CopyStrings(buffer + cch[0], &cch[1], tail...); | |
} | |
template <typename T, typename ...Ts> | |
int concat(uint_t *pcch, T **ppout, const T *head, const Ts *...tail) | |
{ | |
uint_t offsets[sizeof...(tail) + 1] = {}; | |
uint_t cch = StringsLengths(offsets, head, tail...) + 1; | |
T *pOut = (T*)malloc(cch * sizeof(T)); | |
if (pOut == nullptr) { | |
return -ENOMEM; | |
} | |
CopyStrings(pOut, offsets, head, tail...); | |
pOut[cch - 1] = 0; | |
*pcch = cch; | |
*ppout = pOut; | |
return 0; | |
} | |
int main(int argc, char *argv[]) { | |
const char a[] ="fdas."; | |
const char b[] = "swag."; | |
char *res = NULL; | |
uint_t cch = 0; | |
concat(&cch, &res, "yolo.", "swag.", a, "hak", b, "fda"); | |
printf("%d %s\n", cch, res); | |
//printf("%s\n", res); | |
//concat(&res, a, b); | |
//printf("%s\n", res); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment