From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from mo4-p00-ob.smtp.rzone.de ([81.169.146.163]:13750 "EHLO mo4-p00-ob.smtp.rzone.de" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1751966AbaBSOq7 (ORCPT ); Wed, 19 Feb 2014 09:46:59 -0500 Message-ID: <5304C3DF.90002@giantdisaster.de> Date: Wed, 19 Feb 2014 15:46:55 +0100 From: Stefan Behrens MIME-Version: 1.0 To: Wang Shilong , linux-btrfs@vger.kernel.org Subject: Re: [PATCH 1/4] Btrfs-progs: new helper to parse string to u64 for btrfs References: <1392808674-21656-1-git-send-email-wangsl.fnst@cn.fujitsu.com> <1392808674-21656-2-git-send-email-wangsl.fnst@cn.fujitsu.com> In-Reply-To: <1392808674-21656-2-git-send-email-wangsl.fnst@cn.fujitsu.com> Content-Type: text/plain; charset=UTF-8 Sender: linux-btrfs-owner@vger.kernel.org List-ID: On Wed, 19 Feb 2014 19:17:51 +0800, Wang Shilong wrote: > There are many places that need parse string to u64 for btrfs commands, > in fact, we do such things *too casually*, using atoi/atol/atoll..is not > right at all, and even we don't check whether it is a valid string. > > Let's do everything more gracefully, we introduce a new helper > btrfs_strtoull() which will do all the necessary checks.If we fail to > parse string to u64, we will output message and exit directly, this is > something like what usage() is doing. It is ok to not return erro to > it's caller, because this function should be called when parsing arg > (just like usage!) > > Signed-off-by: Wang Shilong > --- > utils.c | 19 +++++++++++++++++++ > utils.h | 1 + > 2 files changed, 20 insertions(+) > > diff --git a/utils.c b/utils.c > index 97e23d5..0698d8d 100644 > --- a/utils.c > +++ b/utils.c > @@ -1520,6 +1520,25 @@ scan_again: > return 0; > } > > +u64 btrfs_strtoull(char *str, int base) > +{ > + u64 value; > + char *ptr_parse_end = NULL; > + char *ptr_str_end = str + strlen(str); > + > + value = strtoull(str, &ptr_parse_end, base); > + if (ptr_parse_end != ptr_str_end) { > + fprintf(stderr, "ERROR: %s is not an invalid unsigned long long integer.\n", "not invalid" :) > + str); > + exit(1); > + } > + if (value == ULONG_MAX) { ULLONG_MAX or {errno = 0; value = strtoull(...); if (errno == ERANGE)...} > + fprintf(stderr, "ERROR: %s is out of range.\n", str); > + exit(1); > + } base = 0 is best BTW since it is able to read hex and octal numbers as well. I'd remove the base parameter to btrfs_strtoull() and always use 0.