3
/* Swap two streams. If the second argument is NULL,
4
** a new stream will be created. Always return the second argument
5
** or the new stream. Note that this function will always work
6
** unless streams are locked by SF_PUSH.
8
** Written by Kiem-Phong Vo.
12
Sfio_t* sfswap(reg Sfio_t* f1, reg Sfio_t* f2)
20
int f1pool, f2pool, f1mode, f2mode, f1flags, f2flags;
22
if(!f1 || (f1->mode&SF_AVAIL) || (SFFROZEN(f1) && (f1->mode&SF_PUSH)) )
24
if(f2 && SFFROZEN(f2) && (f2->mode&SF_PUSH) )
31
f1->mode |= SF_PUSH; /* make sure there is no recursion on f1 */
36
f2->mode |= SF_PUSH; /* make sure there is no recursion on f2 */
39
{ f2 = f1->file == 0 ? sfstdin :
40
f1->file == 1 ? sfstdout :
41
f1->file == 2 ? sfstderr : NIL(Sfio_t*);
42
if((!f2 || !(f2->mode&SF_AVAIL)) )
43
{ if(!(f2 = (Sfio_t*)malloc(sizeof(Sfio_t))) )
49
SFCLEAR(f2,NIL(Vtmutex_t*));
51
f2->mode = SF_AVAIL|SF_LOCK;
57
else for(f1pool = f1->pool->n_sf-1; f1pool >= 0; --f1pool)
58
if(f1->pool->sf[f1pool] == f1)
62
else for(f2pool = f2->pool->n_sf-1; f2pool >= 0; --f2pool)
63
if(f2->pool->sf[f2pool] == f2)
69
/* swap image and pool entries */
70
memcpy((Void_t*)(&tmp),(Void_t*)f1,sizeof(Sfio_t));
71
memcpy((Void_t*)f1,(Void_t*)f2,sizeof(Sfio_t));
72
memcpy((Void_t*)f2,(Void_t*)(&tmp),sizeof(Sfio_t));
74
f1->pool->sf[f2pool] = f1;
76
f2->pool->sf[f1pool] = f2;
79
f2->flags |= SF_STATIC;
80
else f2->flags &= ~SF_STATIC;
83
f1->flags |= SF_STATIC;
84
else f1->flags &= ~SF_STATIC;
86
if(f2mode&SF_AVAIL) /* swapping to a closed stream */
87
{ if(!(f1->flags&SF_STATIC) )