Thu, 22 Jan 2015 13:21:57 +0100
Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6
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/. */
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.
11 #include "hnjalloc.h"
12 #include "nsNetUtil.h"
14 #define BUFSIZE 1024
16 struct hnjFile_ {
17 nsCOMPtr<nsIInputStream> mStream;
18 char mBuffer[BUFSIZE];
19 uint32_t mCurPos;
20 uint32_t mLimit;
21 };
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");
31 nsCOMPtr<nsIURI> uri;
32 nsresult rv = NS_NewURI(getter_AddRefs(uri), aURISpec);
33 if (NS_FAILED(rv)) {
34 return nullptr;
35 }
37 nsCOMPtr<nsIInputStream> instream;
38 rv = NS_OpenURI(getter_AddRefs(instream), uri);
39 if (NS_FAILED(rv)) {
40 return nullptr;
41 }
43 hnjFile *f = new hnjFile;
44 f->mStream = instream;
45 f->mCurPos = 0;
46 f->mLimit = 0;
48 return f;
49 }
51 // replacement for fclose()
52 int
53 hnjFclose(hnjFile* f)
54 {
55 NS_ASSERTION(f && f->mStream, "bad argument to hnjFclose");
57 int result = 0;
58 nsresult rv = f->mStream->Close();
59 if (NS_FAILED(rv)) {
60 result = EOF;
61 }
62 f->mStream = nullptr;
64 delete f;
65 return result;
66 }
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");
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 }
86 f->mCurPos = 0;
88 nsresult rv = f->mStream->Read(f->mBuffer, BUFSIZE, &f->mLimit);
89 if (NS_FAILED(rv)) {
90 f->mLimit = 0;
91 return nullptr;
92 }
94 if (f->mLimit == 0) {
95 break;
96 }
97 }
99 if (i == 0) {
100 return nullptr; // end of file
101 }
103 s[i] = '\0'; // null-terminate the returned string
104 return s;
105 }