You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

MemmappedFileSystem.cs 2.6 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*****************************************************************************
  2. Copyright 2021 The TensorFlow.NET Authors. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ******************************************************************************/
  13. using System;
  14. using System.IO;
  15. using System.IO.MemoryMappedFiles;
  16. using System.Linq;
  17. using Tensorflow;
  18. namespace Tensorflow.IO
  19. {
  20. public class MemmappedFileSystem
  21. {
  22. public const string MEMMAPPED_PACKAGE_DEFAULT_NAME = "memmapped_package://.";
  23. private MemoryMappedFile _mmapFile;
  24. private MemmappedFileSystemDirectory _directory;
  25. public MemmappedFileSystem(string path)
  26. {
  27. using (var stream = File.OpenRead(path))
  28. {
  29. // Read the offset for the directory
  30. var offsetData = new byte[sizeof(ulong)];
  31. stream.Seek(-sizeof(ulong), SeekOrigin.End);
  32. stream.Read(offsetData, 0, sizeof(ulong));
  33. var offset = BitConverter.ToUInt64(offsetData, 0);
  34. var dirLength = stream.Length - (long) offset - sizeof(ulong);
  35. if (dirLength < 0)
  36. {
  37. throw new InvalidDataException("Malformed mmapped filesystem!");
  38. }
  39. var dirData = new byte[dirLength];
  40. stream.Seek((long) offset, SeekOrigin.Begin);
  41. stream.Read(dirData, 0, (int) dirLength);
  42. _directory = MemmappedFileSystemDirectory.Parser.ParseFrom(dirData);
  43. }
  44. _mmapFile = MemoryMappedFile.CreateFromFile(path, FileMode.Open);
  45. }
  46. public Stream OpenMemmapped(string filename)
  47. {
  48. var entry = _directory.Element.FirstOrDefault(x => x.Name == filename);
  49. if (entry == null)
  50. {
  51. throw new FileNotFoundException($"Missing memmaped file entry: {filename}");
  52. }
  53. return _mmapFile.CreateViewStream((long) entry.Offset, (long) entry.Length);
  54. }
  55. }
  56. }