Skip to content

Commit 3bce846

Browse files
committed
Implement mmap.resize on POSIX
1 parent a858fcd commit 3bce846

File tree

1 file changed

+31
-6
lines changed

1 file changed

+31
-6
lines changed

Src/IronPython.Modules/mmap.cs

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Licensed to the .NET Foundation under one or more agreements.
1+
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
33
// See the LICENSE file in the project root for more information.
44

@@ -825,12 +825,37 @@ public void resize(long newsize) {
825825
throw PythonOps.TypeError("mmap can't resize a readonly or copy-on-write memory map.");
826826
}
827827

828-
if (_sourceStream == null) {
829-
if (_handle is not null && !_handle.IsInvalid
830-
&& (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux))) {
831-
// resize on Posix platforms
832-
PythonNT.ftruncateUnix(unchecked((int)_handle.DangerousGetHandle()), newsize);
828+
if (_handle is not null
829+
&& (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux))) {
830+
// resize on Posix platforms
831+
try {
832+
if (_handle.IsInvalid) {
833+
throw PythonOps.OSError(PythonErrorNumber.EBADF, "Bad file descriptor");
834+
}
835+
_view.Flush();
836+
_view.Dispose();
837+
_file.Dispose();
838+
839+
// Resize the underlying file as needed.
840+
int fd = unchecked((int)_handle.DangerousGetHandle());
841+
PythonNT.ftruncateUnix(fd, newsize);
842+
843+
#if NET8_0_OR_GREATER
844+
_file = MemoryMappedFile.CreateFromFile(_handle, _mapName, newsize, _fileAccess, HandleInheritability.None, leaveOpen: true);
845+
#else
846+
_sourceStream?.Dispose();
847+
_sourceStream = new FileStream(new SafeFileHandle((IntPtr)fd, ownsHandle: false), FileAccess.ReadWrite);
848+
_file = CreateFromFile(_sourceStream, _mapName, newsize, _fileAccess, HandleInheritability.None, leaveOpen: true);
849+
#endif
850+
_view = _file.CreateViewAccessor(_offset, newsize, _fileAccess);
851+
return;
852+
} catch {
853+
close();
854+
throw;
833855
}
856+
}
857+
858+
if (_sourceStream == null) {
834859
// resizing is not supported without an underlying file
835860
throw WindowsError(PythonExceptions._OSError.ERROR_INVALID_PARAMETER);
836861
}

0 commit comments

Comments
 (0)