c_cpp C中不可变数据框架的原型

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp C中不可变数据框架的原型相关的知识,希望对你有一定的参考价值。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Prototype for Immutable Data API in C
 * Allows data to be structured immutablely via blocks of ints
 * int fit into word size and ar emore expressive in a binary manner,
 * int can store length, size, of object, uchar is too small.
 * Meant to be used in functional frameworks or new frameworks.
*/

/** Denotes the amount of 32-BIT signed integers to represent an immutable int
  */
#define IMMUTABLE_INT_SIZE 2

/** Data info enum
* enum allows consistent enumeration over data markers.
* When traversing the int* data, this allows *data == immutable_kind
* comps to be made.
*/
typedef enum
{
	immutable_kind_int
} immutable_kind;

/* Data values struct
 * Here, the first int of data is the size, or number of
 * 32-bit signed int in the type. The rest of the data
 * values is padded after on the struct. Always allocated onto the struct
 * via malloc
 *
*/
typedef struct
{
	int data[1];
} immutable_t;

immutable_t* immutable_new(int size)
{
	immutable_t* new_im = malloc(sizeof(immutable_t) + sizeof(int) * size);
	*(new_im->data) = size;
	return new_im;
}

// Gets amount of 32-bit signed in the chunk.
int immutable_get_size(immutable_t* im)
{
	return im->data[0];
}

size_t immutable_real_size(immutable_t* im)
{
	return sizeof(immutable_t) + im->data[0] * sizeof(int);
}

// Constructor function that makes an immutable int inside immutable_t
// Writes the type marker as immutable_kind_int
immutable_t* immutable_make_int(int number)
{
	immutable_t* new_im = malloc(sizeof(immutable_t) + sizeof(int) * IMMUTABLE_INT_SIZE);
	new_im->data[0] = immutable_kind_int;
	new_im->data[1] = number;
	return new_im;
}

int main(int argc, char const *argv[])
{
	printf("sizeof immutable_t is %lu\n", sizeof(immutable_t));
	immutable_t* test = immutable_new(3);
	printf("sizeof this instance is %d\n", immutable_get_size(test));
	printf("real size of this instance is %lu\n", immutable_real_size(test));
	free(test);
	return 0;
}

以上是关于c_cpp C中不可变数据框架的原型的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp c中自我评估型系统的原型。

c_cpp 基于图形编程的原型潜力

c_cpp 在c中实现sha256的原型

c_cpp 反应式编程系统的原型

c_cpp 另一个使用c ++ 11和可变参数模板的代理

c_cpp 可评估语言的第一个原型