问题描述
我正在尝试将代码库从 C 移植到 Rust。类型转换是非常隐含的,手动尝试控制内存使得找出最佳解决方案变得非常困难。我试图移植的数据结构实现了一个哈希表:
// An entry in the hash table
typedef struct DataEntryStruct
{
char *key;
int data;
struct DataEntryStruct *next;
} DataEntry;
typedef struct DataEntryStruct *HashTable;
// Hash a string to an integer
unsigned int gethash(char *str)
{
unsigned int hash = 5381;
unsigned int retHash;
int c;
while ((c = *str++))
{
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
retHash = hash % HASHTABLEMAXSIZE;
return retHash;
}
// Produce a duplicate string
char *dupstr(const char *s)
{
size_t size = strlen(s) + 1;
char *p = malloc(size);
if (p) memcpy(p,s,size);
return p;
}
// Create a hash table
HashTable *hashtable_create()
{
int i;
HashTable *ht = (HashTable *) calloc(HASHTABLEMAXSIZE,sizeof(HashTable));
if (ht != NULL)
{
for (i = 0; i < HASHTABLEMAXSIZE; i++) ht[i] = NULL;
}
return ht;
}
我想我已经弄清楚如何实现第一个块,但不是最后一个带内存分配的块:
struct DataEntry {
key: &str,data: u32,next: Option<&mut HashTable>,}
let HashTable = &mut DataEntry;
// get hash for a string
fn gethash(val: &str) -> u32 {
let mut hash: u32 = 5381;
for c in val.chars() {
hash = (hash << 5 as u32).wrapping_add(hash).wrapping_add(c as u32);
}
return hash % HASHTABLEMAXSIZE;
}
// Produce a duplcate string
fn dupstr(val: &str) -> &str {
// only use rust .clone func
val.clone()
}
如何在尽可能真实地实现hashtable_create
?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)