dm: add string convert API

As function sscanf is banned, to get value from parameter buffer,strto*
is recommended. To reduce the inspection code when using strto*, it's
better to use a string convert API.

Usage:
    For virtio-blk, it has parameters:
        range=<start lba>/<subfile size>
    sscanf:
        if (sscanf(cp, "range=%ld/%ld", &sub_file_start_lba,
                &sub_file_size) == 2)
            sub_file_assign = 1;
    string API:
        if (strsep(&cp, "=") &&
                !dm_strtol(cp, &cp, 10, &sub_file_start_lba) &&
                *cp == '/' &&
                !dm_strtol(cp + 1, &cp, 10, &sub_file_size))
            sub_file_assign = 1;

Tracked-on: #1496
Signed-off-by: Conghui Chen <conghui.chen@intel.com>
Reviewed-by: Shuo Liu <shuo.a.liu@intel.com>
Acked-by: Yin Fengwei <fengwei.yin@intel.com>
This commit is contained in:
Conghui Chen
2018-10-17 02:50:04 +08:00
committed by wenlingz
parent 4620b935de
commit e1dab512c2
3 changed files with 139 additions and 0 deletions

View File

@@ -0,0 +1,69 @@
/*
* Copyright (C) 2018 Intel Corporation. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "dm_string.h"
int
dm_strtol(char *s, char **end, unsigned int base, long *val)
{
if (!s)
goto err;
*val = strtol(s, end, base);
if (*end == s) {
printf("ERROR! nothing covert for: %s!\n", s);
goto err;
}
return 0;
err:
return -1;
}
int
dm_strtoi(char *s, char **end, unsigned int base, int *val)
{
long l_val;
int ret;
l_val = 0;
ret = dm_strtol(s, end, base, &l_val);
*val = (int)l_val;
return ret;
}
int
dm_strtoul(char *s, char **end, unsigned int base, unsigned long *val)
{
if (!s)
goto err;
*val = strtoul(s, end, base);
if (*end == s) {
printf("ERROR! nothing covert for: %s!\n", s);
goto err;
}
return 0;
err:
return -1;
}
int
dm_strtoui(char *s, char **end, unsigned int base, unsigned int *val)
{
unsigned long l_val;
int ret;
l_val = 0;
ret = dm_strtoul(s, end, base, &l_val);
*val = (unsigned int)l_val;
return ret;
}