4 // Copyright (C) 2004 Novell, Inc.
8 // Permission is hereby granted, free of charge, to any person obtaining a copy
9 // of this software and associated documentation files (the "Software"), to deal
10 // in the Software without restriction, including without limitation the rights
11 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 // copies of the Software, and to permit persons to whom the Software is
13 // furnished to do so, subject to the following conditions:
15 // The above copyright notice and this permission notice shall be included in all
16 // copies or substantial portions of the Software.
18 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 using System
.Collections
;
32 namespace Beagle
.Util
{
34 public class PullingReader
: TextReader
{
36 private string identifier
;
38 public string Identifier
{
39 get { return identifier; }
40 set { identifier = value; }
43 //////////////////////////
45 public delegate bool Pull (StringBuilder buffer
);
48 StringBuilder pullBuffer
= new StringBuilder ();
51 public PullingReader (Pull _pull
) : base ()
56 private void DoPull (int neededSize
)
58 while (! done
&& pullBuffer
.Length
< neededSize
) {
60 done
= ! pull (pullBuffer
);
61 } catch (Exception e
) {
62 Logger
.Log
.Debug ("Caught exception pulling text from {0}", pull
);
68 public override void Close ()
73 public override int Peek ()
76 return done
? -1 : (int) pullBuffer
[0];
79 public override int Read ()
84 int x
= (int) pullBuffer
[0];
85 pullBuffer
.Remove (0, 1);
89 public override int Read (char[] buffer
, int index
, int count
)
92 if (done
&& pullBuffer
.Length
< count
)
93 count
= pullBuffer
.Length
;
95 for (int i
= 0; i
< count
; ++i
)
96 buffer
[index
+ i
] = pullBuffer
[i
];
97 pullBuffer
.Remove (0, count
);
102 public override int ReadBlock (char[] buffer
, int index
, int count
)
104 return Read (buffer
, index
, count
);
107 public override string ReadLine ()
118 while (i
< pullBuffer
.Length
) {
119 if (pullBuffer
[i
] == '\n') {
120 string foo
= pullBuffer
.ToString (0, i
);
121 pullBuffer
.Remove (0, i
+1);
127 // If there is nothing else to pull, just return everything
130 string str
= pullBuffer
.ToString ();
131 pullBuffer
.Length
= 0;
135 DoPull (2 * pullBuffer
.Length
);
139 public override string ReadToEnd ()
142 DoPull (2 * pullBuffer
.Length
);
144 string str
= pullBuffer
.ToString ();
145 pullBuffer
.Length
= 0;