Re: [PATCH] Add function to_oct

John Naylor <john.naylor@enterprisedb.com>

From: John Naylor <john.naylor@enterprisedb.com>
To: Nathan Bossart <nathandbossart@gmail.com>
Cc: Kirk Wolak <wolakk@gmail.com>, Peter Eisentraut <peter.eisentraut@enterprisedb.com>, Eric Radman <ericshane@eradman.com>, pgsql-hackers@postgresql.org
Date: 2023-08-19T04:41:56Z
Lists: pgsql-hackers
On Thu, Aug 17, 2023 at 10:26 PM Nathan Bossart <nathandbossart@gmail.com>
wrote:
>
> On Thu, Aug 17, 2023 at 12:35:54PM +0700, John Naylor wrote:
> > That makes it a lexically-scoped global variable, which we don't need
> > either. Can we have the internal function allocate on the stack, then
> > call cstring_to_text() on that, returning the text result? That does its
> > own palloc.
> >
> > Or maybe better, save the starting pointer, compute the length at the
end,
> > and call cstring_to_text_with_len()?  (It seems we wouldn't need
> > the nul-terminator then, either.)
>
> Works for me.  I did it that way in v7.

This looks nicer, but still doesn't save the starting pointer, and so needs
to lug around that big honking macro. This is what I mean:

static inline text *
convert_to_base(uint64 value, int base)
{
  const char *digits = "0123456789abcdef";
  /* We size the buffer for to_binary's longest possible return value. */
  char    buf[sizeof(uint64) * BITS_PER_BYTE];
  char     * const end =  buf + sizeof(buf);
  char     *ptr = end;

  Assert(base > 1);
  Assert(base <= 16);

  do
  {
    *--ptr = digits[value % base];
    value /= base;
  } while (ptr > buf && value);

  return cstring_to_text_with_len(ptr,  end - ptr);
}

--
John Naylor
EDB: http://www.enterprisedb.com

Commits

  1. Add to_bin() and to_oct().