summaryrefslogtreecommitdiff
path: root/src/mt/mstream.cc
blob: 3d9493638977c74e8d9f409c66dcce9ff6a32212 (plain)
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
/*************************************************************************
 *
 * HTCd - Copyright (C) 1998-2006 Henrik Rydberg
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <mt/mstream.h>
#include <poll.h>
#include <signal.h>

const char cvt_form_f[]="%#.12f";
const int MSEC=4000;

sref ftoa(sref_t& buf,double f)
{
  char* e=buf+sprintf(buf,cvt_form_f,f)-1;
  while(*e=='0') e--; if(*e=='.') e--;
  return sref(buf,e-buf+1);
}

///////////////////////////////////////////////////////////

int mstream::appc(char c) { return -1; }
int mstream::appi(int i) { return -1; }
int mstream::appf(double f) { return -1; }
int mstream::apps(const sref& s) { return -1; }

///////////////////////////////////////////////////////////

int cvt_stream::appi(int i) { sref_t buf; return apps(itoa(buf,i)); }
int cvt_stream::appf(double f) { sref_t buf; return apps(ftoa(buf,f)); }

///////////////////////////////////////////////////////////

int fp_stream::appc(char c) { return putc(c,fp)<0?-1:1; }
int fp_stream::apps(const sref& s) { return fwrite(s.data(),s.size(),1,fp); }

///////////////////////////////////////////////////////////

int fd_stream::appc(char c) { return ::write(fd,&c,1); }
int fd_stream::apps(const sref& s) { return ::write(fd,s.data(),s.size()); }

///////////////////////////////////////////////////////////

int pipe_stream::appc(char c) { return mwrite(&c,1); }
int pipe_stream::apps(const sref& s) { return mwrite(s.data(),s.size()); }

int pipe_stream::mwrite(const char* s,int n)
{
  int old=n;
  while(n>0&&!hup) {
    pollfd pfd={fd,POLLOUT,0};
    if(::poll(&pfd,1,MSEC)<0) return hup=-1;
    int m=::write(fd,s,n);
    if(m<0) return hup=-1;
    s+=m; n-=m;
  }
  return hup?-1:old;
}