|
|
#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
|
|
|
}
|