mirror of
https://git.libssh.org/projects/libssh.git
synced 2026-02-05 04:40:31 +09:00
feat(string): add ssh_string_cmp function for comparing ssh_strings
Signed-off-by: Praneeth Sarode <praneethsarode@gmail.com> Reviewed-by: Jakub Jelen <jjelen@redhat.com>
This commit is contained in:
committed by
Jakub Jelen
parent
3423399f98
commit
95f8cbc7f0
52
src/string.c
52
src/string.c
@@ -27,8 +27,8 @@
|
||||
#include <limits.h>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#endif
|
||||
|
||||
#include "libssh/priv.h"
|
||||
@@ -244,6 +244,56 @@ struct ssh_string_struct *ssh_string_copy(struct ssh_string_struct *s)
|
||||
return new;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Compare two SSH strings.
|
||||
*
|
||||
* @param[in] s1 The first SSH string to compare.
|
||||
* @param[in] s2 The second SSH string to compare.
|
||||
*
|
||||
* @return 0 if the strings are equal,
|
||||
* < 0 if s1 is less than s2,
|
||||
* > 0 if s1 is greater than s2.
|
||||
*/
|
||||
int ssh_string_cmp(struct ssh_string_struct *s1, struct ssh_string_struct *s2)
|
||||
{
|
||||
size_t len1, len2, min_len;
|
||||
int cmp;
|
||||
|
||||
/* Both are NULL */
|
||||
if (s1 == NULL && s2 == NULL) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Only one is NULL - NULL is considered "less than" non-NULL */
|
||||
if (s1 == NULL) {
|
||||
return -1;
|
||||
} else if (s2 == NULL) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Get lengths */
|
||||
len1 = ssh_string_len(s1);
|
||||
len2 = ssh_string_len(s2);
|
||||
min_len = MIN(len1, len2);
|
||||
|
||||
/* Compare data up to the shorter length */
|
||||
if (min_len > 0) {
|
||||
cmp = memcmp(s1->data, s2->data, min_len);
|
||||
if (cmp != 0) {
|
||||
return cmp;
|
||||
}
|
||||
}
|
||||
|
||||
/* If common prefix is equal, compare lengths */
|
||||
if (len1 < len2) {
|
||||
return -1;
|
||||
} else if (len1 > len2) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Destroy the data in a string so it couldn't appear in a core dump.
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user