1 /***********************************************************************
3 * This software is part of the ast package *
4 * Copyright (c) 1985-2010 AT&T Intellectual Property *
5 * and is licensed under the *
6 * Common Public License, Version 1.0 *
7 * by AT&T Intellectual Property *
9 * A copy of the License is available at *
10 * http://www.opensource.org/licenses/cpl1.0.txt *
11 * (with md5 checksum 059e8cd6165cb4c31e351f2b69388fd9) *
13 * Information and Software Systems Research *
17 * Glenn Fowler <gsf@research.att.com> *
18 * David Korn <dgk@research.att.com> *
19 * Phong Vo <kpv@research.att.com> *
21 ***********************************************************************/
25 * a discipline that prepends a prefix string to each output line
30 * @(#)$Id: sfdcprefix (AT&T Research) 1998-06-25 $
35 Sfdisc_t disc
; /* sfio discipline */
36 size_t length
; /* prefix length */
37 size_t empty
; /* empty line prefix length */
38 int skip
; /* this line already prefixed */
39 char prefix
[1]; /* prefix string */
47 static ssize_t
pfxwrite(Sfio_t
* f
, const Void_t
* buf
, register size_t n
, Sfdisc_t
* dp
)
49 static ssize_t
pfxwrite(f
, buf
, n
, dp
)
56 register Prefix_t
* pfx
= (Prefix_t
*)dp
;
71 if (!(t
= memchr(s
, '\n', e
- s
)))
80 sfwr(f
, pfx
->prefix
, n
> 1 ? pfx
->length
: pfx
->empty
, dp
);
81 w
+= sfwr(f
, s
, n
, dp
);
84 } while ((s
= t
+ 1) < e
);
91 * remove the discipline on close
95 static int pfxexcept(Sfio_t
* f
, int type
, Void_t
* data
, Sfdisc_t
* dp
)
97 static int pfxexcept(f
, type
, data
, dp
)
104 if (type
== SF_FINAL
|| type
== SF_DPOP
)
110 * push the prefix discipline on f
114 int sfdcprefix(Sfio_t
* f
, const char* prefix
)
116 int sfdcprefix(f
, prefix
)
121 register Prefix_t
* pfx
;
126 * this is a writeonly discipline
129 if (!prefix
|| !(n
= strlen(prefix
)) || !(sfset(f
, 0, 0) & SF_WRITE
))
131 if (!(pfx
= (Prefix_t
*)malloc(sizeof(Prefix_t
) + n
)))
133 memset(pfx
, 0, sizeof(*pfx
));
135 pfx
->disc
.writef
= pfxwrite
;
136 pfx
->disc
.exceptf
= pfxexcept
;
138 memcpy(pfx
->prefix
, prefix
, n
);
139 s
= (char*)prefix
+ n
;
140 while (--s
> (char*)prefix
&& (*s
== ' ' || *s
== '\t'));
141 n
= s
- (char*)prefix
;
142 if (*s
!= ' ' || *s
!= '\t')
146 if (sfdisc(f
, &pfx
->disc
) != &pfx
->disc
)