tweak usage of str replacement code

This commit is contained in:
NunoSempere 2024-03-23 17:54:15 -03:00
parent 5097a1982b
commit e322621698
2 changed files with 25 additions and 41 deletions

View File

@ -6,15 +6,13 @@
#define LIBRE_N 50
/* Inspired by https://libredirect.github.io/, but in C. */
// Use string manipulation over urls
int libre_redirect(const char* uri, char* output)
{
int len_uri = strlen(uri);
int len_output = strlen(output);
if ((len_output - len_uri) < LIBRE_N) {
printf("Not enough memory\n");
fprintf(stderr, "Not enough memory\n");
return 1; // not enough memory.
} else {
char* annoying_sites[] = {
@ -52,14 +50,14 @@ int libre_redirect(const char* uri, char* output)
case 0: // no match found
break;
case 1: // str_replace_start somehow failed
printf("str_replace_start failed\n");
fprintf(stderr, "str_replace_start failed\n");
return 1;
break;
case 2: // match succeeded
return 2;
break;
default:
printf("Unreachable state");
fprintf(stderr, "Unreachable state\n");
}
}
strcpy(output, uri);

View File

@ -5,30 +5,18 @@
#include "../strings/strings.h"
#define SHORTCUT_N 41
/* Uncomment for debug */
/* #define DEBUG */
#define DEBUG false
/* Inspired by https://duckduckgo.com/bangs */
int shortcut_expand(const char* uri, char* output)
{
printf("SHORTCUT EXPAND!\n");
int l1 = strlen(uri);
int l2 = strlen(output);
int len;
char tmp_uri[l2++];
char tmp_output[l2++];
int len_uri = strlen(uri);
int len_output = strlen(output);
if ((l2 - l1) < SHORTCUT_N) {
#ifdef DEBUG
printf("Not enough memory\n");
#endif
if ((len_output - len_uri) < SHORTCUT_N) {
fprintf(stderr, "Not enough memory\n");
return 1; // not enough memory.
} else {
strcpy(tmp_uri, uri); // strcpy also copies the terminating '\0'
strcpy(tmp_output, output);
char* shortcuts[] = {
"!aa",
"!blog",
@ -50,30 +38,28 @@ int shortcut_expand(const char* uri, char* output)
};
// len = sizeof(shortcuts) / sizeof(shortcuts[0]);
len = sizeof(shortcuts) / sizeof(char*);
int len = sizeof(shortcuts) / sizeof(char*);
for (int i = 0; i < len; i++) {
int replace_check = str_replace_start(tmp_uri, shortcuts[i],
str_init(output, len_output);
int replace_check = str_replace_start(uri, shortcuts[i],
expansions[i], output);
if (replace_check == 2) {
#ifdef DEBUG
printf("tmp_uri: %s\n", tmp_uri);
printf("output: %s\n", output);
#endif
return 2;
} else if (replace_check == 1) {
#ifdef DEBUG
printf("replace_check failed\n");
#endif
return 1;
switch (replace_check) {
case 0: // no match found
break;
case 1: // str_replace_start somehow failed
fprintf(stderr, "str_replace_start failed\n");
return 1;
break;
case 2: // match succeeded
return 2;
break;
default:
fprintf(stderr, "Unreachable state\n");
}
strcpy(tmp_uri, output);
str_init(output, l2);
}
strcpy(output, tmp_uri);
strcpy(output, uri);
}
#ifdef DEBUG
printf("No match found\n\n");
#endif
if(DEBUG) printf("No match found\n\n");
return 0;
}