|
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ |
|
2 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
3 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
5 |
|
6 // This file provides substitutes for the basic stdio routines used by hyphen.c |
|
7 // to read its dictionary files. We #define the stdio names to these versions |
|
8 // in hnjalloc.h, so that we can use nsIURI and nsIInputStream to specify and |
|
9 // access the dictionary resources. |
|
10 |
|
11 #include "hnjalloc.h" |
|
12 #include "nsNetUtil.h" |
|
13 |
|
14 #define BUFSIZE 1024 |
|
15 |
|
16 struct hnjFile_ { |
|
17 nsCOMPtr<nsIInputStream> mStream; |
|
18 char mBuffer[BUFSIZE]; |
|
19 uint32_t mCurPos; |
|
20 uint32_t mLimit; |
|
21 }; |
|
22 |
|
23 // replacement for fopen() |
|
24 // (not a full substitute: only supports read access) |
|
25 hnjFile* |
|
26 hnjFopen(const char* aURISpec, const char* aMode) |
|
27 { |
|
28 // this override only needs to support "r" |
|
29 NS_ASSERTION(!strcmp(aMode, "r"), "unsupported fopen() mode in hnjFopen"); |
|
30 |
|
31 nsCOMPtr<nsIURI> uri; |
|
32 nsresult rv = NS_NewURI(getter_AddRefs(uri), aURISpec); |
|
33 if (NS_FAILED(rv)) { |
|
34 return nullptr; |
|
35 } |
|
36 |
|
37 nsCOMPtr<nsIInputStream> instream; |
|
38 rv = NS_OpenURI(getter_AddRefs(instream), uri); |
|
39 if (NS_FAILED(rv)) { |
|
40 return nullptr; |
|
41 } |
|
42 |
|
43 hnjFile *f = new hnjFile; |
|
44 f->mStream = instream; |
|
45 f->mCurPos = 0; |
|
46 f->mLimit = 0; |
|
47 |
|
48 return f; |
|
49 } |
|
50 |
|
51 // replacement for fclose() |
|
52 int |
|
53 hnjFclose(hnjFile* f) |
|
54 { |
|
55 NS_ASSERTION(f && f->mStream, "bad argument to hnjFclose"); |
|
56 |
|
57 int result = 0; |
|
58 nsresult rv = f->mStream->Close(); |
|
59 if (NS_FAILED(rv)) { |
|
60 result = EOF; |
|
61 } |
|
62 f->mStream = nullptr; |
|
63 |
|
64 delete f; |
|
65 return result; |
|
66 } |
|
67 |
|
68 // replacement for fgets() |
|
69 // (not a full reimplementation, but sufficient for libhyphen's needs) |
|
70 char* |
|
71 hnjFgets(char* s, int n, hnjFile* f) |
|
72 { |
|
73 NS_ASSERTION(s && f, "bad argument to hnjFgets"); |
|
74 |
|
75 int i = 0; |
|
76 while (i < n - 1) { |
|
77 if (f->mCurPos < f->mLimit) { |
|
78 char c = f->mBuffer[f->mCurPos++]; |
|
79 s[i++] = c; |
|
80 if (c == '\n' || c == '\r') { |
|
81 break; |
|
82 } |
|
83 continue; |
|
84 } |
|
85 |
|
86 f->mCurPos = 0; |
|
87 |
|
88 nsresult rv = f->mStream->Read(f->mBuffer, BUFSIZE, &f->mLimit); |
|
89 if (NS_FAILED(rv)) { |
|
90 f->mLimit = 0; |
|
91 return nullptr; |
|
92 } |
|
93 |
|
94 if (f->mLimit == 0) { |
|
95 break; |
|
96 } |
|
97 } |
|
98 |
|
99 if (i == 0) { |
|
100 return nullptr; // end of file |
|
101 } |
|
102 |
|
103 s[i] = '\0'; // null-terminate the returned string |
|
104 return s; |
|
105 } |