xref: /haiku/src/apps/mediaplayer/support/FileReadWrite.cpp (revision b55a57da7173b9af0432bd3e148d03f06161d036)
1 /*
2  * Copyright 2008, Haiku.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Michael Pfeiffer 	<laplace@users.sourceforge.net>
7  *		Fredrik Modéen		<fredrik@modeen.se>
8  */
9 #include "FileReadWrite.h"
10 
11 #include <UTF8.h>
12 #include <Path.h>
13 
14 
15 FileReadWrite::FileReadWrite(BFile* file, int32 sourceEncoding)
16 	: fFile(file),
17 	  fSourceEncoding(sourceEncoding),
18 	  fPositionInBuffer(0),
19 	  fAmtRead(0)
20 {}
21 
22 
23 void
24 FileReadWrite::SetEncoding(int32 sourceEncoding)
25 {
26 	fSourceEncoding = sourceEncoding;
27 }
28 
29 
30 uint32
31 FileReadWrite::GetEncoding() const
32 {
33 	return fSourceEncoding;
34 }
35 
36 
37 status_t
38 FileReadWrite::Write(const BString& contents) const
39 {
40 	ssize_t written = fFile->Write(contents.String(), contents.Length());
41 	if (written != contents.Length())
42 		return written < 0 ? (status_t)written : B_IO_ERROR;
43 
44 	return B_OK;
45 }
46 
47 
48 bool
49 FileReadWrite::Next(BString& string)
50 {
51 	// Fill up the buffer with the first chunk of data
52 	if (fPositionInBuffer == 0)
53 		fAmtRead = fFile->Read(&fBuffer, sizeof(fBuffer));
54 	while (fAmtRead > 0) {
55 		while (fPositionInBuffer < fAmtRead) {
56 			// Return true if we hit a newline or the end of the file
57 			if (fBuffer[fPositionInBuffer] == '\n') {
58 				fPositionInBuffer++;
59 				// Convert begin
60 				int32 state = 0;
61 				int32 bufferLen = string.Length();
62 				int32 destBufferLen = bufferLen;
63 				char destination[destBufferLen];
64 				if (fSourceEncoding) {
65 					convert_to_utf8(fSourceEncoding, string.String(),
66 						&bufferLen, destination, &destBufferLen, &state);
67 				}
68 				string = destination;
69 				return true;
70 			}
71 			string += fBuffer[fPositionInBuffer];
72 			fPositionInBuffer++;
73 		}
74 
75 		// Once the buffer runs out, grab some more and start again
76 		fAmtRead = fFile->Read(&fBuffer, sizeof(fBuffer));
77 		fPositionInBuffer = 0;
78 	}
79 	return false;
80 }
81