/*
 * nvmem.h
 *
 *  Created on: 2023年10月26日
 *      Author: huaqiyan
 */

#ifndef NVMEM_H_
#define NVMEM_H_

/*
 * Nonvolatile memory object
 */
typedef struct nvmem nvmem_t;

struct nvmem_vtbl {
	/*
	 * @brief initial nvmem object
	 * @param p nvmem object to initial
	 * @param config config file path, default NULL
	 * @return 0 on success, -1 on failure, and errno will be set to indicate an error.
	 */
	int (*init)(nvmem_t *p, const char *config);

	/*
	 * @brief write data to nvmem room
	 * @param p nvmem ovject to write
	 * @param offset bytes offset from 0 of the nvmem room start to write
	 * @param buf the buffer hold the data to write into nvmem
	 * @param bytes length to write
	 * @return return bytes has written on success, -1 on failure and errno will be set indicate an error
	 */
	int (*write)(nvmem_t *p, int offset, void *buf, int bytes);

	/*
	 * @brief read data from nvmem room
	 * @param p nvmem ovject to read
	 * @param offset bytes offset from 0 of the nvmem room start to read
	 * @param buf the buffer to receive data read from nvmem
	 * @param bytes length to read
	 * @return return bytes has read on success, -1 on failure and errno will be set indicate an error
	 */
	int (*read)(nvmem_t *p, int offset, void *buf, int bytes);
};

struct nvmem {
	const struct nvmem_vtbl *lpvtbl;
};

#define nvmem_init(p, c) \
	(p)->lpvtbl->init(p, c)

#define nvmem_write(p, o, b, n) \
	(p)->lpvtbl->write(p, o, b, n)

#define nvmem_read(p, o, b, n) \
		(p)->lpvtbl->read(p, o, b, n)

/*
 * constructor & destructor
 */
nvmem_t* nvmem_create(void);
void nvmem_free(nvmem_t *p);

#endif /* NVMEM_H_ */
