1/**
2 * Copyright (c) Glow Contributors. See CONTRIBUTORS file.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "glow/Base/IO.h"
18
19#include "llvm/Support/FileSystem.h"
20
21#include <glog/logging.h>
22
23#include <cstdio>
24#include <sys/stat.h>
25#include <sys/types.h>
26
27namespace glow {
28
29void writeToFile(const Tensor &T, llvm::StringRef filename) {
30 FILE *fp = fopen(filename.data(), "wb");
31 CHECK(fp) << "Failed to open file: " << filename.str();
32 auto nitems = fwrite(&T.getType(), sizeof(Type), 1, fp);
33 CHECK_EQ(nitems, 1);
34 nitems = fwrite(T.getUnsafePtr(), T.getType().getElementSize(), T.size(), fp);
35 CHECK_EQ(nitems, T.size());
36 fclose(fp);
37}
38
39void readFromFile(Tensor &T, llvm::StringRef filename) {
40 FILE *fp = fopen(filename.data(), "rb");
41 CHECK(fp) << "Failed to open file: " << filename.str();
42 Type type;
43 auto nitems = fread(&type, sizeof(Type), 1, fp);
44 CHECK_EQ(nitems, 1);
45 T.reset(type);
46 nitems = fread(T.getUnsafePtr(), T.getType().getElementSize(), T.size(), fp);
47 CHECK_EQ(nitems, T.size());
48 fclose(fp);
49}
50
51} // namespace glow
52