• sds.c(一)


    #include <stdio.h>
    #include <string.h>
    #include "zmalloc.h"
    #include "testhelp.h"
    
    typedef char *sds;
    
    struct sdshdr {
        unsigned int len;
        unsigned int free;
        char buf[];
    };
    
    static inline size_t sdslen(const sds s) {
        printf("sizeof(struct sdshdr)=%d
    ",sizeof(struct sdshdr));
        struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
        printf("sh->buf=%s
    ",sh->buf);
        printf("sh->len=%d
    ",sh->len);
        return sh->len;
    }
    
    /* Create a new sds string with the content specified by the 'init' pointer
     * and 'initlen'.
     * If NULL is used for 'init' the string is initialized with zero bytes.
     *
     * The string is always null-termined (all the sds strings are, always) so
     * even if you create an sds string with:
     *
     * mystring = sdsnewlen("abc",3);
     *
     * You can print the string with printf() as there is an implicit  at the
     * end of the string. However the string is binary safe and can contain
     *  characters in the middle, as the length is stored in the sds header. */
    sds sdsnewlen(const void *init, size_t initlen) {
        struct sdshdr *sh;
        
        printf("***sdsnewlen init=%s len=%d***
    ",init,initlen);
        printf("sizeof(struct sdshdr)+initlen+1=%d***
    ",sizeof(struct sdshdr)+initlen+1);
        if (init) {
            sh = zmalloc(sizeof(struct sdshdr)+initlen+1);
        } else {
            sh = zcalloc(sizeof(struct sdshdr)+initlen+1);
        }
        if (sh == NULL) return NULL;
        sh->len = initlen;
        sh->free = 0;
        if (initlen && init)
            memcpy(sh->buf, init, initlen);
        sh->buf[initlen] = '';
        return (char*)sh->buf;
    }
    
    /* Create a new sds string starting from a null termined C string. */
    sds sdsnew(const char *init) {
        size_t initlen = (init == NULL) ? 0 : strlen(init);
        return sdsnewlen(init, initlen);
    }
    
    int main()
    {
    
        struct sdshdr *sh;
        sds x = sdsnew("foo"), y;
    
        test_cond("Create a string and obtain the length",
            sdslen(x) == 3 && memcmp(x,"foo",4) == 0);
        
        
    }
    
    /*
    gcc sds.c zmalloc.c
    [root@rac1 Sds]# ./a.out 123 ***sdsnewlen init=foo len=3*** sizeof(struct sdshdr)+initlen+1=12*** 1 - Create a string and obtain the length: sizeof(struct sdshdr)=8 sh->buf=foo sh->len=3 PASSED */
  • 相关阅读:
    【洛谷P5305】旧词
    【洛谷P5470】序列
    【CF865D】Buy Low Sell High
    【洛谷P3242】接水果
    【洛谷P5048】Yuno loves sqrt technology III
    一、Java语言基础(1)_走进java——JDK-JRE-JVM概述
    一、Java语言基础(1)_走进java——跨平台/可移植性
    第一阶段:前端开发_JavaScript基础
    第一阶段:前端开发_HTML表单&CSS
    第一阶段:前端开发_HTML&CSS
  • 原文地址:https://www.cnblogs.com/huanhuanang/p/4524175.html
Copyright © 2020-2023  润新知