Skip to content

Commit 1ab75c4

Browse files
committed
fix loading multiple chunks in memory
1 parent 44c6f33 commit 1ab75c4

File tree

4 files changed

+41
-1
lines changed

4 files changed

+41
-1
lines changed

CHANGELOG.md

+6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# Changelog
22

3+
## [Unreleased]
4+
5+
### Fixed
6+
7+
- `Innmind\Filesystem\File\Content::ofChunks()->size()` no longer load more than one chunk size in memory
8+
39
## 7.5.0 - 2024-03-16
410

511
### Changed

fixtures/sample.pdf

5.68 MB
Binary file not shown.

proofs/file/content.php

+24
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
<?php
22
declare(strict_types = 1);
3+
declare(ticks = 1);
34

45
use Innmind\Filesystem\File\{
56
Content as Model,
@@ -238,4 +239,27 @@ static function($assert, $a, $b) use ($io, $capabilities) {
238239
$assert->throws(static fn() => $b($content));
239240
},
240241
);
242+
243+
yield test(
244+
'Content::ofChunks()->size() does not load the whole file in memory',
245+
static function($assert) use ($io, $capabilities) {
246+
$atPath = Model::atPath(
247+
$capabilities->readable(),
248+
$io,
249+
Path::of('fixtures/sample.pdf'),
250+
);
251+
$content = Model::ofChunks($atPath->chunks());
252+
253+
$assert
254+
->memory(static function() use ($assert, $content) {
255+
$size = $content->size()->match(
256+
static fn($size) => $size->toInt(),
257+
static fn() => null,
258+
);
259+
$assert->same(5951532, $size);
260+
})
261+
->inLessThan()
262+
->kilobytes(600);
263+
},
264+
);
241265
};

src/File/Content/Chunks.php

+11-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
namespace Innmind\Filesystem\File\Content;
55

6+
use Innmind\Stream\Stream\Size;
67
use Innmind\Immutable\{
78
Sequence,
89
SideEffect,
@@ -81,7 +82,16 @@ public function reduce($carry, callable $reducer)
8182

8283
public function size(): Maybe
8384
{
84-
return $this->content()->size();
85+
return Maybe::just(
86+
$this
87+
->chunks
88+
->map(static fn($chunk) => $chunk->toEncoding(Str\Encoding::ascii))
89+
->map(static fn($chunk) => $chunk->length())
90+
->reduce(
91+
0,
92+
static fn(int $total, int $chunk) => $total + $chunk,
93+
),
94+
)->map(static fn($size) => new Size($size));
8595
}
8696

8797
public function toString(): string

0 commit comments

Comments
 (0)