Calculates the checksum of the header block.

The checksum is calculated by taking the sum of the unsigned byte values of the header
record with the eight checksum bytes taken to be ascii spaces (decimal value 32).

@param string $headerBlock

@return int
352606
protected function calculateChecksum($headerBlock)
    {
        $checksum = 0;
        for ($i = 0; $i<self::SIZE_HEADER_BLOCK; $i++) {
            if ($i < 148 || $i >= 156) {
                $checksum += ord($headerBlock[$i]);
            } else {
                $checksum += 32;
            }
        }

        return $checksum;
    }
1271629
public static function parseBlock($block)
    {
        $data = array();
        $lines = preg_split("/(\r\n|\n|\r)/", trim($block));
        $continueKey = null;
        foreach($lines as $n => $line) {
            if ($continueKey !== null) {
                $data[$continueKey] .= "\n" . $line;
                if (!self::lineContinues($lines, $n, $continueKey)) {
                    $continueKey = null;
                }
            } elseif (preg_match('/([^:]*): ?(.*)/', $line, $match)) {
                $key = $match[1];
                $value = $match[2];
                // Convert multiple keys like 'FieldStateOption' or 'FieldValue'
                // from Choice fields to array
                if (isset($data[$key])) {
                    $data[$key]   = (array) $data[$key];
                    $data[$key][] = $value;
                } else {
                    $data[$key] = $value;
                }
                if (self::lineContinues($lines, $n, $key)) {
                    $continueKey = $key;
                }
            }
        }
        return $data;
    }
544296
public function write(string $bytes): int
    {
        $isAcceptable = $this->predicate;
        if ($isAcceptable($bytes)) {
            return $this->outputStream->write($bytes);
        }

        return 0;
    }
964852
protected function process_header($block, $handler) {
        // If the block consists entirely of nulls, ignore it. (This happens
        // twice at end of archive.)
        if ($block === str_pad('', tgz_packer::TAR_BLOCK_SIZE, "\0")) {
            return;
        }

        // struct header_posix_ustar {
        //    char name[100];
        $name = rtrim(substr($block, 0, 100), "\0");

        //    char mode[8];
        //    char uid[8];
        //    char gid[8];
        //    char size[12];
        $filesize = octdec(substr($block, 124, 11));

        //    char mtime[12];
        $mtime = octdec(substr($block, 136, 11));

        //    char checksum[8];
        //    char typeflag[1];
        $typeflag = substr($block, 156, 1);

        //    char linkname[100];
        //    char magic[6];
        $magic = substr($block, 257, 6);
        if ($magic !== "ustar\0" && $magic !== "ustar ") {
            // There are two checks above; the first is the correct POSIX format
            // and the second is for GNU tar default format.
            throw new moodle_exception('errorprocessingarchive', '', '', null,
                    'Header does not have POSIX ustar magic string');
        }

        //    char version[2];
        //    char uname[32];
        //    char gname[32];
        //    char devmajor[8];
        //    char devminor[8];
        //    char prefix[155];
        $prefix = rtrim(substr($block, 345, 155), "\0");

        //    char pad[12];
        // };

        $archivepath = ltrim($prefix . '/' . $name, '/');

        // For security, ensure there is no .. folder in the archivepath.
        $archivepath = clean_param($archivepath, PARAM_PATH);

        // Handle file depending on the type.
        switch ($typeflag) {
            case '1' :
            case '2' :
            case '3' :
            case '4' :
            case '6' :
            case '7' :
                // Ignore these special cases.
                break;

            case '5' :
                // Directory.
                if ($this->mode === self::MODE_LIST) {
                    $this->listresults[] = (object)array(
                            'original_pathname' => $archivepath,
                            'pathname' => $archivepath,
                            'mtime' => $mtime,
                            'is_directory' => true,
                            'size' => 0);
                } else if ($handler->tgz_directory($archivepath, $mtime)) {
                    $this->results[$archivepath] = true;
                }
                break;

            default:
                // All other values treated as normal file.
                $this->start_current_file($archivepath, $filesize, $mtime, $handler);
                break;
        }
    }
1351614
private function pad($string, $block = 32)
    {
        $pad = $block - (strlen($string) % $block);

        return $string . str_repeat(chr($pad), $pad);
    }
714063
static public int getBlockCrc(DataNode datanode, ReplicaToRead ri,
      int namespaceId, Block block) throws IOException {

    InputStream rawStreamIn = null;
    DataInputStream streamIn = null;
    int blockCrc = 0;

    try {
      int bytesPerCRC;
      int checksumSize;

      bytesPerCRC = ri.getBytesPerChecksum();
      int checksumType = ri.getChecksumType();
      if (checksumType != DataChecksum.CHECKSUM_CRC32) {
        throw new IOException("File Checksum now is only supported for CRC32");
      }
      DataChecksum dataChecksum = DataChecksum.newDataChecksum(checksumType,
          bytesPerCRC);
      checksumSize = dataChecksum.getChecksumSize();
      
      rawStreamIn = ri.getBlockInputStream(datanode, 0);
      streamIn = new DataInputStream(new BufferedInputStream(rawStreamIn,
          FSConstants.BUFFER_SIZE));
      IOUtils.skipFully(streamIn, BlockInlineChecksumReader.getHeaderSize());

      long lengthLeft = ((FileInputStream) rawStreamIn).getChannel().size()
          - BlockInlineChecksumReader.getHeaderSize();
      if (lengthLeft == 0) {
        blockCrc = (int) dataChecksum.getValue();
      } else {
        byte[] buffer = new byte[checksumSize];
        boolean firstChecksum = true;

        while (lengthLeft > 0) {
          long dataByteLengh;

          if (lengthLeft >= bytesPerCRC + checksumSize) {
            lengthLeft -= bytesPerCRC + checksumSize;
            dataByteLengh = bytesPerCRC;
          } else if (lengthLeft > checksumSize) {
            dataByteLengh = lengthLeft - checksumSize;
            lengthLeft = 0;
          } else {
            // report to name node the corruption.
            DataBlockScanner.reportBadBlocks(block, namespaceId, datanode);
            throw new IOException("File for namespace " + namespaceId
                + " block " + block + " seems to be corrupted");
          }

          IOUtils.skipFully(streamIn, dataByteLengh);
          IOUtils.readFully(streamIn, buffer, 0, buffer.length);
          int intChecksum = DataChecksum.getIntFromBytes(buffer, 0);
          if (firstChecksum) {
            blockCrc = intChecksum;
            firstChecksum = false;
          } else {
            blockCrc = CrcConcat.concatCrc(blockCrc, intChecksum,
                (int) dataByteLengh);
          }
        }
      }

      if (LOG.isDebugEnabled()) {
        LOG.debug("block=" + block + ", bytesPerCRC=" + bytesPerCRC
            + ", crc=" + blockCrc);
      }
      return blockCrc;
    } finally {
      IOUtils.closeStream(streamIn);
      IOUtils.closeStream(rawStreamIn);
    }

  }
658791
public static long getFileLengthFromBlockSize(long blockSize,
      int bytesPerChecksum, int checksumSize) {
    long numChunks; 
    if (blockSize % bytesPerChecksum == 0) {    
      numChunks = blockSize / bytesPerChecksum; 
    } else {    
      numChunks = blockSize / bytesPerChecksum + 1; 
    }   
    return blockSize + numChunks * checksumSize 
        + BlockInlineChecksumReader.getHeaderSize();  
  }
1212162
void getBlockChecksum(DataInputStream in,
      VersionAndOpcode versionAndOpcode) throws IOException {
    // header
    BlockChecksumHeader blockChecksumHeader =
        new BlockChecksumHeader(versionAndOpcode);
    blockChecksumHeader.readFields(in);
    final int namespaceId = blockChecksumHeader.getNamespaceId();
    final Block block = new Block(blockChecksumHeader.getBlockId(), 0,
            blockChecksumHeader.getGenStamp());

    DataOutputStream out = null;
    InputStream rawStreamIn = null;
    DataInputStream streamIn = null;

    ReplicaToRead ri = datanode.data.getReplicaToRead(namespaceId, block);
    if (ri == null) {
      throw new IOException("Unknown block");
    }

    updateCurrentThreadName("getting checksum for block " + block);
    try {
      int bytesPerCRC;
      int checksumSize;

      long crcPerBlock;
      MD5Hash md5;
      if (!ri.isInlineChecksum()) {
        rawStreamIn = BlockWithChecksumFileReader.getMetaDataInputStream(
            datanode.data, namespaceId, block);
        streamIn = new DataInputStream(new BufferedInputStream(rawStreamIn,
            BUFFER_SIZE));

        final BlockMetadataHeader header = BlockMetadataHeader
            .readHeader(streamIn);
        final DataChecksum checksum = header.getChecksum();
        bytesPerCRC = checksum.getBytesPerChecksum();
        checksumSize = checksum.getChecksumSize();
        crcPerBlock = (((BlockWithChecksumFileReader.MetaDataInputStream) rawStreamIn)
            .getLength() - BlockMetadataHeader.getHeaderSize()) / checksumSize;

       //compute block checksum
       md5 = MD5Hash.digest(streamIn);
      } else {
        bytesPerCRC = ri.getBytesPerChecksum();
        checksumSize = DataChecksum.getChecksumSizeByType(ri.getChecksumType());
        ReplicaToRead replica = datanode.data.getReplicaToRead(namespaceId, block);
        rawStreamIn = replica.getBlockInputStream(datanode, 0);
        streamIn = new DataInputStream(new BufferedInputStream(rawStreamIn,
            BUFFER_SIZE));

        long lengthLeft = ((FileInputStream) rawStreamIn).getChannel().size()
            - BlockInlineChecksumReader.getHeaderSize();
        if (lengthLeft == 0) {
          crcPerBlock = 0;
          md5 = MD5Hash.digest(new byte[0]);
        } else {
          crcPerBlock = (lengthLeft - 1) / (checksumSize + bytesPerCRC) + 1;
          MessageDigest digester = MD5Hash.getDigester();
          byte[] buffer = new byte[checksumSize];
          while (lengthLeft > 0) {
            if (lengthLeft >= bytesPerCRC + checksumSize) {
              streamIn.skip(bytesPerCRC);
              IOUtils.readFully(streamIn, buffer, 0, buffer.length);
              lengthLeft -= bytesPerCRC
                  + checksumSize;
            } else if (lengthLeft > checksumSize) {
              streamIn.skip(lengthLeft - checksumSize);
              IOUtils.readFully(streamIn, buffer, 0, buffer.length);
              lengthLeft = 0;
            } else {
              out = new DataOutputStream(
                  NetUtils.getOutputStream(s, datanode.socketWriteTimeout));
              out.writeShort(DataTransferProtocol.OP_STATUS_ERROR);
              out.flush();
              // report to name node the corruption.
              DataBlockScanner.reportBadBlocks(block, namespaceId, datanode);
              throw new IOException("File for namespace " + namespaceId
                  + " block " + block + " seems to be corrupted");
            }
            digester.update(buffer);
          }
          md5 = new MD5Hash(digester.digest(), checksumSize * crcPerBlock);
        }
      }

      if (LOG.isDebugEnabled()) {
        LOG.debug("block=" + block + ", bytesPerCRC=" + bytesPerCRC
            + ", crcPerBlock=" + crcPerBlock + ", md5=" + md5);
      }

      //write reply
      out = new DataOutputStream(
          NetUtils.getOutputStream(s, datanode.socketWriteTimeout));
      out.writeShort(DataTransferProtocol.OP_STATUS_SUCCESS);
      out.writeInt(bytesPerCRC);
      out.writeLong(crcPerBlock);
      md5.write(out);
      out.flush();
    } finally {
      IOUtils.closeStream(out);
      if (streamIn != null) {
        IOUtils.closeStream(streamIn);
      }
      if (rawStreamIn != null) {
        IOUtils.closeStream(rawStreamIn);
      }
    }
  }
85349
def calculate_block_size
      char_amount = 1
      base_length = @oracle.encipher(DUMMY * char_amount).length
      result = nil
      (1..MAX_KNOWN_BLOCK_LENGTH).each do |length|
        new_length   = @oracle.encipher(DUMMY * char_amount).length
        if new_length > base_length
          result = new_length - base_length
          break
        end
        char_amount += 1
      end
      result
    end
1095241
protected function consolidate(): int
    {
        $bytes = 0;
        if ("\n" !== $this->newline) {
            $this->document->fseek(-1, SEEK_CUR);
            $bytes = $this->document->fwrite($this->newline, strlen($this->newline)) - 1;
        }

        if (null === $this->flush_threshold) {
            return $bytes;
        }

        ++$this->flush_counter;
        if (0 === $this->flush_counter % $this->flush_threshold) {
            $this->flush_counter = 0;
            $this->document->fflush();
        }

        return $bytes;
    }
1125913
public function sortBlocks(array $blocks)
    {
        // Perform a simple sort first
        usort($blocks, function ($a, $b)  {
            if ($a->getSort() == $b->getSort()) {
                return 0;
            }
            return ($a->getSort() < $b->getSort()) ? -1 : 1;
        });

        // Determine hierarchy of ownership first
        $ownerIds = array();
        foreach ($blocks as $block) {
            $superKey = ($block->getOwner()->getSuper()) ? array_search($block->getOwner()->getSuper()->getId(), $ownerIds) : false;
            if ($superKey === false) {
                array_unshift($ownerIds, $block->getOwner()->getId());
            } else {
                $ownerIds = array_merge(array_slice($ownerIds, 0, $superKey+1), array($block->getOwner()->getId()), array_slice($ownerIds, $superKey+1));
            }
        }
        $ownerIds = array_flip($ownerIds); // Flip it for easier lookup by parentId as key.
        asort($ownerIds);

        $sorted = array();
        $parentOwnerId = null;
        $parentSize = null;
        foreach ($ownerIds as $ownerId => $ownerPos) {
            // Get blocks in level/segment
            $segment = array_values(array_filter($blocks, function ($block) use ($ownerId) {
                return ($block->getOwner() && $block->getOwner()->getId() == $ownerId);
            }));

            if (! count($segment)) {
                $parentOwnerId = $ownerId;
                continue; // nothing to do for this owner
            }

            // now inject at correct positions
            if (count($segment) && $parentOwnerId === null) {
                $sorted = $segment;
            } else if (count($segment)) {
                $positioned = array_filter($segment, function ($block) {
                   return ($block->getSortParent() !== null && $block->getSortParent() >= 0);
                });

                // if nothing is positioned throw them on top
                if (! count($positioned)) {
                    $sorted = array_merge($segment, $sorted);
                } else {
                    // first part
                    $keys = array_keys($positioned);
                    if ($keys[0] > 0) {
                        $sorted = array_merge(array_slice($segment, 0, array_shift($keys)), $sorted);
                    } elseif ($keys[0] == 0) {
                        unset($keys[0]);
                    }

                    foreach ($positioned as $key => $block) {
                        $endIdx = (count($keys)) ? array_shift($keys) : null;
                        $insert = array_slice($segment, $key, ($endIdx) ? ($endIdx-$key) : null);

                        foreach ($sorted as $insertIdx => $item) {
                            // Check if we inherit from this block
                            if ($item->getOwner()->getId() == $parentOwnerId && $item->getSort() == $block->getSortParent() &&
                                // And check if we're in the same parent block on same position
                                (($item->isInRoot() && $block->isInRoot() || ($item->getParent() && $block->getParent() && $item->getParent()->getId() == $block->getParent()->getId())) && $item->getPosition() == $block->getPosition())) {
                                break;
                            }
                        }
                        $sorted = array_merge(array_slice($sorted, 0, $insertIdx+1), $insert, array_slice($sorted, $insertIdx+1));
                    }
                }
            }

            $parentOwnerId = $ownerId;
        }

        return $sorted;
    }
1300166
protected static function calculate_checksum($str) {
        $checksum = 0;
        $checklength = strlen($str);
        for ($i = 0; $i < $checklength; $i++) {
            $checksum += ord($str[$i]);
        }
        return $checksum;
    }
179641
public function checksum($value)
    {
        $checksum = $this->getChecksum();
        if (!empty($checksum)) {
            if (method_exists($this, $checksum)) {
                return call_user_func(array($this, $checksum), $value);
            }
        }

        return false;
    }
576460
protected function calculateChecksum() {
        // Checksum
        // First CheckSUM "C"
        // The "C" checksum character is the modulo 47 remainder of the sum of the weighted
        // value of the data characters. The weighting value starts at "1" for the right-most
        // data character, 2 for the second to last, 3 for the third-to-last, and so on up to 20.
        // After 20, the sequence wraps around back to 1.

        // Second CheckSUM "K"
        // Same as CheckSUM "C" but we count the CheckSum "C" at the end
        // After 15, the sequence wraps around back to 1.
        $sequence_multiplier = array(20, 15);
        $this->checksumValue = array();
        $indcheck = $this->indcheck;
        for ($z = 0; $z < 2; $z++) {
            $checksum = 0;
            for ($i = count($indcheck), $j = 0; $i > 0; $i--, $j++) {
                $multiplier = $i % $sequence_multiplier[$z];
                if ($multiplier === 0) {
                    $multiplier = $sequence_multiplier[$z];
                }

                $checksum += $indcheck[$j] * $multiplier;
            }

            $this->checksumValue[$z] = $checksum % 47;
            $indcheck[] = $this->checksumValue[$z];
        }
    }
434947
private static function encodeFlags(Header $header): int
    {
        return 0x0 |
            ($header->isResponse() & 0x1) << 15 |
            ($header->getOpcode() & 0xf) << 11 |
            ($header->isAuthoritative() & 0x1) << 10 |
            ($header->isTruncated() & 0x1) << 9 |
            ($header->isRecursionDesired() & 0x1) << 8 |
            ($header->isRecursionAvailable() & 0x1) << 7 |
            ($header->getZ() & 0x7) << 4 |
            ($header->getRcode() & 0xf);
    }
900816
private static function getPaddedBlock($bytesIn,$start,$end,$mode){
		if($end - $start > 16)
			$end = $start + 16;

		$xarray = array_slice($bytesIn, $start, $end-$start);

		$cpad = 16 - count($xarray);

		while(count($xarray) < 16){
			array_push($xarray, $cpad);
		}

		return $xarray;
	}
664266
protected function getDocblockTagsSection($docblock)
    {
        $docblock = $this->sanitizeDocblock($docblock);
        preg_match('/^\s*\\'.self::TOKEN_ANNOTATION_IDENTIFIER.'/m', $docblock, $matches, PREG_OFFSET_CAPTURE);

        // return found docblock tag section or empty string
        return isset($matches[0]) ? substr($docblock, $matches[0][1]) : '';
    }