File: path.c

package info (click to toggle)
tra 20020816-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k, sarge
  • size: 1,696 kB
  • ctags: 2,623
  • sloc: ansic: 22,519; makefile: 406; asm: 269
file content (145 lines) | stat: -rw-r--r-- 1,975 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include "tra.h"

/* BUG: keep a free list here? */
void
freepath(Path *p)
{
	if(p==nil)
		return;
	if(--p->ref == 0){
		freepath(p->up);
		free(p->s);
		memset(p, 0xAA, sizeof(Path));
		free(p);
	}
}

Path*
mkpath(Path *up, char *s)
{
	Path *p;

	p = emalloc(sizeof(Path));
	p->up = up;
	if(up)
		up->ref++;
	p->s = estrdup(s);
	p->ref = 1;
	setmalloctag(p, getcallerpc(&up));
	return p;
}

static void
_writebufpath(Buf *b, Path *p, int depth)
{
	if(p){
		_writebufpath(b, p->up, depth+1);
		writebufstring(b, p->s);
	}else
		writebufl(b, depth);
}

void
writebufpath(Buf *b, Path *p)
{
	writebufc(b, 0);
	_writebufpath(b, p, 0);
}

Path*
readbufpath(Buf *b)
{
	int i, n;
	Path *p;

	if(readbufc(b) != 0)
		longjmp(b->jmp, BufData);

	p = nil;
	n = readbufl(b);
	for(i=0; i<n; i++){
		if(p)
			p->ref--;
		p = mkpath(p, readbufstringdup(b));
	}
	setmalloctag(p, getcallerpc(&b));
	return p;
}

static int
_pathfmt(Fmt *fmt, Path *p)
{
	if(p == nil)
		return fmtstrcpy(fmt, "/");
	_pathfmt(fmt, p->up);
	if(p->up != nil)
		fmtstrcpy(fmt, "/");
	return fmtstrcpy(fmt, p->s);
}

int
pathfmt(Fmt *fmt)
{
	Path *p;

	p = va_arg(fmt->args, Path*);
	return _pathfmt(fmt, p);
}

Apath*
flattenpath(Path *p)
{
	char *s;
	int n, ns;
	Apath *ap;
	Path *q;

	n = 0;
	ns = 0;
	for(q=p; q; q=q->up){
		ns += strlen(q->s)+1;
		n++;
	}

	ap = emalloc(sizeof(Apath)+n*sizeof(char*)+ns);
	ap->e = (char**)&ap[1];
	ap->n = n;
	s = (char*)&ap->e[n];
	for(q=p; q; q=q->up){
		strcpy(s, q->s);
		ap->e[--n] = s;
		s += strlen(s)+1;
	}
	setmalloctag(ap, getcallerpc(&p));
	return ap;
}

Apath*
mkapath(char *s)
{
	int n;
	char *t;
	Apath *ap;

	n = 1;
	for(t=s; *t; t++)
		if(*t == '/')
			n++;

	ap = emalloc(sizeof(Apath)+sizeof(char*)*n);
	ap->e = (char**)&ap[1];
	ap->n = 0;
	for(t=s; *t; ){
		while(*t == '/')
			*t++ = '\0';
		if(*t == '\0')
			break;
		ap->e[ap->n++] = t;
		while(*t != '\0' && *t != '/')
			t++;
	}
	assert(ap->n <= n);
	setmalloctag(ap, getcallerpc(&s));
	return ap;
}