Skip to content

Commit

Permalink
store: introduce dupe_policy
Browse files Browse the repository at this point in the history
  • Loading branch information
N-R-K committed Jun 18, 2024
1 parent 1113ca8 commit ed276eb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
14 changes: 8 additions & 6 deletions src/store.c
Original file line number Diff line number Diff line change
Expand Up @@ -401,18 +401,20 @@ static int _must_use_ _nonnull_ cs_snip_add(struct clip_store *cs,
* @cs: The clip store to operate on
* @hash: The hash of the content to add
* @content: The content to add to the file
* @dupe_policy: If set to CS_DUPE_KEEP_LAST, will return with -EEXIST when
* trying to insert duplicate entry.
*/
static int _must_use_ _nonnull_ cs_content_add(struct clip_store *cs,
uint64_t hash,
const char *content) {
static int _must_use_ _nonnull_
cs_content_add(struct clip_store *cs, uint64_t hash, const char *content,
enum cs_dupe_policy dupe_policy) {
bool dupe = false;

char dir_path[CS_HASH_STR_MAX];
snprintf(dir_path, sizeof(dir_path), "%" PRIu64, hash);

int ret = mkdirat(cs->content_dir_fd, dir_path, 0700);
if (ret < 0) {
if (errno != EEXIST) {
if (errno != EEXIST || dupe_policy == CS_DUPE_KEEP_LAST) {
return negative_errno();
}
dupe = true;
Expand Down Expand Up @@ -537,7 +539,7 @@ int cs_add(struct clip_store *cs, const char *content, uint64_t *out_hash) {
char line[CS_SNIP_LINE_SIZE];
size_t nr_lines = first_line(content, line);

int ret = cs_content_add(cs, hash, content);
int ret = cs_content_add(cs, hash, content, CS_DUPE_KEEP_ALL);
if (ret < 0) {
return ret;
}
Expand Down Expand Up @@ -767,7 +769,7 @@ int cs_replace(struct clip_store *cs, enum cs_iter_direction direction,
size_t nr_lines = first_line(content, line);
uint64_t hash = djb64_hash(content);
cs_snip_update(snip, hash, line, nr_lines);
ret = cs_content_add(cs, hash, content);
ret = cs_content_add(cs, hash, content, CS_DUPE_KEEP_ALL);
if (ret) {
return ret;
}
Expand Down
11 changes: 11 additions & 0 deletions src/store.h
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,17 @@ enum cs_remove_action {
CS_ACTION_STOP = BIT(2),
};

/**
* What to do when there's a duplicate entry.
*
* @CS_DUPE_KEEP_ALL: Keep all duplicate entries.
* @CS_DUPE_KEEP_LAST: Only keep the newest, do not insert duplicate entries.
*/
enum cs_dupe_policy {
CS_DUPE_KEEP_ALL,
CS_DUPE_KEEP_LAST,
};

struct ref_guard _must_use_ _nonnull_ cs_ref(struct clip_store *cs);
void _nonnull_ cs_unref(struct clip_store *cs);
void _nonnull_ drop_cs_unref(struct ref_guard *guard);
Expand Down

0 comments on commit ed276eb

Please sign in to comment.