path functions

This commit is contained in:
timerix 2022-11-06 00:35:19 +06:00
parent 856a0e3e3e
commit cac7226de1
2 changed files with 35 additions and 6 deletions

View File

@ -1,13 +1,13 @@
#include "filesystem.h" #include "filesystem.h"
char* __path_concat(uint16 n, char* prev_part, ...){ char* __path_concat(uint16 n, ...){
char** parts=(char**)malloc(n*sizeof(char*)); char** parts=(char**)malloc(n*sizeof(char*));
uint32* lengths=malloc(n*sizeof(uint32)); uint32* lengths=malloc(n*sizeof(uint32));
uint32 totalLength=0; uint32 totalLength=0;
// reading args from va_list // reading args from va_list
va_list vl; va_list vl;
va_start(vl, prev_part); va_start(vl, n);
for(uint16 i=0; i<n; i++){ for(uint16 i=0; i<n; i++){
char* part=va_arg(vl,char*); char* part=va_arg(vl,char*);
int16 length=cptr_length(part); int16 length=cptr_length(part);
@ -38,5 +38,18 @@ char* __path_concat(uint16 n, char* prev_part, ...){
} }
char* path_fixSeparators(char* path){ char* path_fixSeparators(char* path){
char* pathCopy=cptr_copy(path);
char c;
while((c=*pathCopy)){
if(c==path_notSep)
*pathCopy=path_sep;
pathCopy++;
}
return pathCopy;
}
Maybe path_throwIfEscapes(char* path){
if(cptr_contains(path,".."))
safethrow(cptr_concat("path <",path,"> uses <..>, that's not allowed"),);
return MaybeNull;
} }

View File

@ -8,12 +8,28 @@ extern "C" {
#if defined(_WIN32) || defined (_WIN64) #if defined(_WIN32) || defined (_WIN64)
static const char path_sep='\\'; static const char path_sep='\\';
static const char path_notSep='/';
#else #else
static const char path_sep='/'; static const char path_sep='/';
static const char path_notSep='\\';
#endif #endif
char* __path_concat(uint16 n, char* path_start, ...); char* __path_concat(uint16 n, ...);
#define path_concat(PATH_PARTS) __path_concat(count_args(PATH_PARTS), PATH_PARTS) /// @brief merges path parts together and places <path_sep> between them
/// @return new cstr
#define path_concat(PATH_PARTS...) __path_concat(count_args(PATH_PARTS), PATH_PARTS)
/// @brief fixes path separators
/// @param cstr where can be <path_notSep>
/// @return new cstr with correct separators
char* path_fixSeparators(char* path);
#define path_resolve(PATH_PARTS...) path_fixSeparators(path_concat(PATH_PARTS))
/// @brief calls safethrow() if finds escape sequense in path
/// @param path cstr where can be <..>
/// @return Maybe<void>
Maybe path_throwIfEscapes(char* path);
#if __cplusplus #if __cplusplus
} }