Subject: Suggested method for creating a string in the server

From: Clay Luther <[email-masked]>
Date: Fri, 24 Jan 1992 14:06:00 -0800

I am adding some functions to the moo server and one of the functions needs
a buffer string to work on.  The exact nature of the call is

foo(anon *p; char *c; char *buf);

Foo works on data from p and c, storing to buf.  The string at buf will
finally be returned to the server.  The problem, of course, is guessing how
big a buf one needs in the first place.

Currently, I am working with this algorithm:

buf = (char *)malloc(some_big_size);
foo(p,c,buf);
r.v.str = strdup(buf);
free(buf);

If there is a better, more Pavelish way, please let me know.

-- 
Clay W. Luther                  [email-masked]
System Manager                  Center for Network Neuroscience
University of North Texas       PO Box 5218 Denton, Texas 76203
817/565-3896,3472               GB-Free in '93.

---

From: Pavel Curtis <[email-masked]>
Date: Fri, 24 Jan 1992 16:41:34 -0800

Clay Luther writes:
> I am adding some functions to the moo server and one of the functions needs a
> buffer string to work on...  The problem, of course, is guessing how big a
> buf one needs in the first place.

The right way to do this is to use the functions declared in streams.h:

	extern Stream  *new_stream(int size);
	extern void	stream_add_char(Stream *, char);
	extern void	stream_add_string(Stream *, const char *);
	extern void	stream_printf(Stream *, const char *, ...);
	extern void	free_stream(Stream *);
	extern char    *stream_contents(Stream *);
	extern char    *reset_stream(Stream *);
	extern int	stream_length(Stream *);

Use new_stream() to get a stream to write on; the argument is a guess at how
many characters you'll write, but it doesn't matter if you're wrong.  Then use
stream_add_char(), stream_add_string(), and stream_printf() to add stuff onto
the end of the stream.  (Note: stream_printf() can only handle %s and %d, not
all of printf.)  At any time, you can use stream_length() to see how many
characters you've got in there so far and stream_contents() to get your hands
on the underlying string itself, null-terminated and all.  reset_stream() both
returns the underlying null-terminated string and changes the state of the
stream to say that it's empty again; this is useful for when you want to reuse
the stream for some other purpose, avoiding the cost of freeing this stream and
making a new one.  Finally, when you're done with the stream, use free_stream()
to get rid of it cleanly.

Note that you should finish using the string returned by stream_contents() and
reset_stream() before calling any of stream_add_char(), stream_add_string(),
stream_printf(), or free_stream() on the corresponding stream; using strdup()
on it is a common way of obeying this rule.

	Pavel