CachedLayer writeTarLayer(DescriptorDigest diffId, Blob compressedBlob) throws IOException {
    Files.createDirectories(cacheStorageFiles.getLocalDirectory());
    Files.createDirectories(cacheStorageFiles.getTemporaryDirectory());
    try (TempDirectoryProvider tempDirectoryProvider = new TempDirectoryProvider()) {
      Path temporaryLayerDirectory =
          tempDirectoryProvider.newDirectory(cacheStorageFiles.getTemporaryDirectory());
      Path temporaryLayerFile = cacheStorageFiles.getTemporaryLayerFile(temporaryLayerDirectory);

      BlobDescriptor layerBlobDescriptor;
      try (OutputStream fileOutputStream =
          new BufferedOutputStream(Files.newOutputStream(temporaryLayerFile))) {
        layerBlobDescriptor = compressedBlob.writeTo(fileOutputStream);
      }

      // Renames the temporary layer file to its digest
      // (temp/temp -> temp/<digest>)
      String fileName = layerBlobDescriptor.getDigest().getHash();
      Path digestLayerFile = temporaryLayerDirectory.resolve(fileName);
      moveIfDoesNotExist(temporaryLayerFile, digestLayerFile);

      // Moves the temporary directory to directory named with diff ID
      // (temp/<digest> -> <diffID>/<digest>)
      Path destination = cacheStorageFiles.getLocalDirectory().resolve(diffId.getHash());
      moveIfDoesNotExist(temporaryLayerDirectory, destination);

      return CachedLayer.builder()
          .setLayerDigest(layerBlobDescriptor.getDigest())
          .setLayerDiffId(diffId)
          .setLayerSize(layerBlobDescriptor.getSize())
          .setLayerBlob(Blobs.from(destination.resolve(fileName)))
          .build();
    }
  }
@Test
  public void testWriteTarLayer() throws IOException {
    Blob uncompressedLayerBlob = Blobs.from("uncompressedLayerBlob");
    DescriptorDigest diffId = getDigest(uncompressedLayerBlob).getDigest();

    CachedLayer cachedLayer =
        cacheStorageWriter.writeTarLayer(diffId, compress(uncompressedLayerBlob));

    BlobDescriptor layerBlobDescriptor = getDigest(compress(uncompressedLayerBlob));

    // Verifies cachedLayer is correct.
    Assert.assertEquals(layerBlobDescriptor.getDigest(), cachedLayer.getDigest());
    Assert.assertEquals(diffId, cachedLayer.getDiffId());
    Assert.assertEquals(layerBlobDescriptor.getSize(), cachedLayer.getSize());
    Assert.assertArrayEquals(
        Blobs.writeToByteArray(uncompressedLayerBlob),
        Blobs.writeToByteArray(decompress(cachedLayer.getBlob())));

    // Verifies that the files are present.
    Assert.assertTrue(
        Files.exists(
            cacheStorageFiles
                .getLocalDirectory()
                .resolve(cachedLayer.getDiffId().getHash())
                .resolve(cachedLayer.getDigest().getHash())));
  }