You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
sledge/runtime/tests/fibonacciadd/dag_data_split.c

100 lines
2.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include "dag_data_split.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct DataNode {
uint32_t dataLength;
char *data;
struct DataNode *next;
};
DataNode* splitData(char *buffer, uint32_t bufferSize) {
DataNode *head = NULL;
DataNode *tail = NULL;
uint32_t offset = 0;
while (offset < bufferSize) {
if (offset + 4 > bufferSize) {
break;
}
uint32_t dataLength = *(uint32_t *)(buffer + offset);
offset += 4;
if (offset + dataLength > bufferSize) {
break;
}
DataNode *newNode = (DataNode *)malloc(sizeof(DataNode));
if (newNode == NULL) {
perror("Memory allocation failed");
freeDataNodes(head); // 释放已分配的节点内存
return NULL;
}
newNode->data = (char *)malloc(dataLength);
if (newNode->data == NULL) {
free(newNode);
perror("Memory allocation failed");
freeDataNodes(head); // 释放已分配的节点内存
return NULL;
}
memcpy(newNode->data, buffer + offset, dataLength);
newNode->dataLength = dataLength;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
tail->next = newNode;
}
tail = newNode;
offset += dataLength;
}
return head;
}
void freeDataNodes(DataNode *head) {
while (head != NULL) {
DataNode *next = head->next;
free(head->data);
free(head);
head = next;
}
}
void printDataList(DataNode *head) {
int index = 0;
DataNode *current = head;
while (current != NULL) {
printf("Data %d: Length = %u\n", index, current->dataLength);
index++;
current = current->next;
}
}
int getDataNodeCount(DataNode *head) {
int count = 0;
DataNode *current = head;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
const char* getDataNodeByIndex(DataNode *head, int index) {
int count = 1;
DataNode *current = head;
while (current != NULL) {
if (count == index) {
return current->data;
}
count++;
current = current->next;
}
return NULL; // 如果索引超出范围返回NULL
}