@param Schema $writers_schema
@param $datum
@param IOBinaryEncoder $encoder
@returns mixed

@throws IOTypeException if $datum is invalid for $writers_schema
491046
function write_data(Schema $writers_schema, $datum, IOBinaryEncoder $encoder)
    {
        if (!Schema::is_valid_datum($writers_schema, $datum))
            throw new IOTypeException($writers_schema, $datum);

        switch ($writers_schema->type()) {
            case Schema::NULL_TYPE:
                return $encoder->write_null($datum);
            case Schema::BOOLEAN_TYPE:
                return $encoder->write_boolean($datum);
            case Schema::INT_TYPE:
                return $encoder->write_int($datum);
            case Schema::LONG_TYPE:
                return $encoder->write_long($datum);
            case Schema::FLOAT_TYPE:
                return $encoder->write_float($datum);
            case Schema::DOUBLE_TYPE:
                return $encoder->write_double($datum);
            case Schema::STRING_TYPE:
                return $encoder->write_string($datum);
            case Schema::BYTES_TYPE:
                return $encoder->write_bytes($datum);
            case Schema::ARRAY_SCHEMA:
                return $this->write_array($writers_schema, $datum, $encoder);
            case Schema::MAP_SCHEMA:
                return $this->write_map($writers_schema, $datum, $encoder);
            case Schema::FIXED_SCHEMA:
                return $this->write_fixed($writers_schema, $datum, $encoder);
            case Schema::ENUM_SCHEMA:
                return $this->write_enum($writers_schema, $datum, $encoder);
            case Schema::RECORD_SCHEMA:
            case Schema::ERROR_SCHEMA:
            case Schema::REQUEST_SCHEMA:
                return $this->write_record($writers_schema, $datum, $encoder);
            case Schema::UNION_SCHEMA:
                return $this->write_union($writers_schema, $datum, $encoder);
            default:
                throw new Exception(sprintf('Uknown type: %s',
                    $writers_schema->type));
        }
    }
1114845
public void ser(Object datum, OutputStream output) throws IOException {
		Map<Class, Serializer> serializers = cachedSerializers.get();
		Serializer ser = serializers.get(datum.getClass());
		if(ser == null) {
			ser = serialization.getSerializer(datum.getClass());
			if(ser == null) {
				throw new IOException("Serializer for class " + datum.getClass() + " not found");
			}
			serializers.put(datum.getClass(), ser);
		}
		ser.open(output);
		ser.serialize(datum);
		ser.close();
	}
1284109
private void generateEncodeBody(GeneratorAdapter mg, Schema schema, TypeToken<?> outputType,
                                  int value, int encoder, int schemaLocal, int seenRefs) {
    Schema.Type schemaType = schema.getType();

    switch (schemaType) {
      case NULL:
        break;
      case BOOLEAN:
        encodeSimple(mg, outputType, schema, "writeBool", value, encoder);
        break;
      case INT:
      case LONG:
      case FLOAT:
      case DOUBLE:
      case BYTES:
      case STRING:
        String encodeMethod = "write" + schemaType.name().charAt(0) + schemaType.name().substring(1).toLowerCase();
        encodeSimple(mg, outputType, schema, encodeMethod, value, encoder);
        break;
      case ENUM:
        encodeEnum(mg, outputType, value, encoder, schemaLocal);
        break;
      case ARRAY:
        if (Collection.class.isAssignableFrom(outputType.getRawType())) {
          Preconditions.checkArgument(outputType.getType() instanceof ParameterizedType,
                                      "Only support parameterized collection type.");
          TypeToken<?> componentType = TypeToken.of(((ParameterizedType) outputType.getType())
                                                      .getActualTypeArguments()[0]);

          encodeCollection(mg, componentType, schema.getComponentSchema(),
                           value, encoder, schemaLocal, seenRefs);
        } else if (outputType.isArray()) {
          TypeToken<?> componentType = outputType.getComponentType();
          encodeArray(mg, componentType, schema.getComponentSchema(),
                      value, encoder, schemaLocal, seenRefs);
        }
        break;
      case MAP:
        Preconditions.checkArgument(Map.class.isAssignableFrom(outputType.getRawType()),
                                    "Only %s type is supported.", Map.class.getName());
        Preconditions.checkArgument(outputType.getType() instanceof ParameterizedType,
                                    "Only support parameterized map type.");
        java.lang.reflect.Type[] mapArgs = ((ParameterizedType) outputType.getType()).getActualTypeArguments();
        Map.Entry<Schema, Schema> mapSchema = schema.getMapSchema();
        encodeMap(mg, TypeToken.of(mapArgs[0]), TypeToken.of(mapArgs[1]),
                  mapSchema.getKey(), mapSchema.getValue(), value, encoder, schemaLocal, seenRefs);
        break;
      case RECORD:
        encodeRecord(mg, schema, outputType, value, encoder, schemaLocal, seenRefs);
        break;
      case UNION:
        encodeUnion(mg, outputType, schema, value, encoder, schemaLocal, seenRefs);
        break;
    }
  }
560718
protected function _encodeWithSchemas()
    {
        if ($this->viewVars['_inflect'] === 'dasherize') {
            $this->_dasherizeIncludesViewVar();
        }

        // All "Schema is not registered for a resource at path 'xyz'" errors
        // originate from the line below and are caused by the mentioned Cake Table
        // object not being present in the  `_repositories` viewVar array.
        $schemas = $this->_entitiesToNeoMerxSchema($this->viewVars['_repositories']);

        // Please note that a third NeoMerx EncoderOptions argument `depth`
        // exists but has not been implemented in this plugin.
        $encoder = Encoder::instance(
            $schemas,
            new EncoderOptions(
                $this->_jsonOptions()
            )
        );

        $serialize = null;
        if (isset($this->viewVars['_serialize'])) {
            $serialize = $this->viewVars['_serialize'];
        }

        if (isset($this->viewVars['_serialize']) && $this->viewVars['_serialize'] !== false) {
            $serialize = $this->_getDataToSerializeFromViewVars($this->viewVars['_serialize']);
        }

        // By default the listener will automatically add all associated data
        // (as produced by containable and thus present in the entity) to the
        // '_include' viewVar which is used to produce the top-level `included`
        // node UNLESS user specified an array with associations using the
        // listener config option `include`.
        //
        // Please be aware that `include` will take precedence over the
        //`getIncludePaths()` method that MIGHT exist in custom NeoMerx schemas.
        //
        // Lastly, listener config option `fieldSets` may be used to limit
        // the fields shown in the result.
        $include = $this->viewVars['_include'];
        $fieldSets = $this->viewVars['_fieldSets'];

        $parameters = new EncodingParameters(
            $include,
            $fieldSets
        );

        // Add optional top-level `version` node to the response if enabled
        // by user using listener config option.
        if ($this->viewVars['_withJsonApiVersion']) {
            if (is_array($this->viewVars['_withJsonApiVersion'])) {
                $encoder->withJsonApiVersion($this->viewVars['_withJsonApiVersion']);
            } else {
                $encoder->withJsonApiVersion();
            }
        }

        // Add top-level `links` node with pagination information (requires
        // ApiPaginationListener which will have set/filled viewVar).
        if (isset($this->viewVars['_pagination'])) {
            $pagination = $this->viewVars['_pagination'];

            $encoder->withLinks($this->_getPaginationLinks($pagination));

            // Additional pagination information has to be in top-level node `meta`
            $this->viewVars['_meta']['record_count'] = $pagination['record_count'];
            $this->viewVars['_meta']['page_count'] = $pagination['page_count'];
            $this->viewVars['_meta']['page_limit'] = $pagination['page_limit'];
        }

        // Add optional top-level `meta` node to the response if enabled by
        // user using listener config option.
        if (!empty($this->viewVars['_meta'])) {
            if (empty($serialize)) {
                return $encoder->encodeMeta($this->viewVars['_meta']);
            } else {
                $encoder->withMeta($this->viewVars['_meta']);
            }
        }

        // JSON API as generated by NeoMerx. When things look off,  start debugging here
        $neoMerxEncodedJson = $encoder->encodeData($serialize, $parameters);

        return $neoMerxEncodedJson;
    }
1056268
public function convertDoctrine1Schema(array $fromPaths, $destPath, $toType, $numSpaces, $extend, OutputInterface $output)
    {
        foreach ($fromPaths as &$dirName) {
            $dirName = realpath($dirName);

            if ( ! file_exists($dirName)) {
                throw new \InvalidArgumentException(
                    sprintf("Doctrine 1.X schema directory '<info>%s</info>' does not exist.", $dirName)
                );
            }

            if ( ! is_readable($dirName)) {
                throw new \InvalidArgumentException(
                    sprintf("Doctrine 1.X schema directory '<info>%s</info>' does not have read permissions.", $dirName)
                );
            }
        }

        if ( ! file_exists($destPath)) {
            throw new \InvalidArgumentException(
                sprintf("Doctrine 2.X mapping destination directory '<info>%s</info>' does not exist.", $destPath)
            );
        }

        if ( ! is_writable($destPath)) {
            throw new \InvalidArgumentException(
                sprintf("Doctrine 2.X mapping destination directory '<info>%s</info>' does not have write permissions.", $destPath)
            );
        }

        $cme = $this->getMetadataExporter();
        $exporter = $cme->getExporter($toType, $destPath);

        if (strtolower($toType) === 'annotation') {
            $entityGenerator = $this->getEntityGenerator();
            $exporter->setEntityGenerator($entityGenerator);

            $entityGenerator->setNumSpaces($numSpaces);

            if ($extend !== null) {
                $entityGenerator->setClassToExtend($extend);
            }
        }

        $converter = new ConvertDoctrine1Schema($fromPaths);
        $metadata = $converter->getMetadata();

        if ($metadata) {
            $output->writeln('');

            foreach ($metadata as $class) {
                $output->writeln(sprintf('Processing entity "<info>%s</info>"', $class->name));
            }

            $exporter->setMetadata($metadata);
            $exporter->export();

            $output->writeln(PHP_EOL . sprintf(
                'Converting Doctrine 1.X schema to "<info>%s</info>" mapping type in "<info>%s</info>"', $toType, $destPath
            ));
        } else {
            $output->writeln('No Metadata Classes to process.');
        }
    }
991584
public static function encode($value, string $type = null): string
    {
        return self::run(self::ENCODER, $value, $type);
    }
535001
@Override
    public int encode ( byte[] dst, int dstIndex ) {
        int start = dstIndex;

        SMBUtil.writeInt2(this.hashAlgos != null ? this.hashAlgos.length : 0, dst, dstIndex);
        SMBUtil.writeInt2(this.salt != null ? this.salt.length : 0, dst, dstIndex + 2);
        dstIndex += 4;

        if ( this.hashAlgos != null ) {
            for ( int hashAlgo : this.hashAlgos ) {
                SMBUtil.writeInt2(hashAlgo, dst, dstIndex);
                dstIndex += 2;
            }
        }

        if ( this.salt != null ) {
            System.arraycopy(this.salt, 0, dst, dstIndex, this.salt.length);
            dstIndex += this.salt.length;
        }

        return dstIndex - start;
    }
220794
def write_data(fo, datum, schema):
    

    record_type = extract_record_type(schema)
    logical_type = extract_logical_type(schema)

    fn = WRITERS.get(record_type)
    if fn:
        if logical_type:
            prepare = LOGICAL_WRITERS.get(logical_type)
            if prepare:
                datum = prepare(datum, schema)
        return fn(fo, datum, schema)
    else:
        return write_data(fo, datum, SCHEMA_DEFS[record_type])
392462
public void encodeType(byte[] frame, int[] limits) {
    JSType.setByte(frame, limits, (byte)JSType.TUPLE);
    JSType.setCount(frame, limits, getFieldCount());
    if (fields != null)
      for (int i = 0; i < fields.length; i++)
        fields[i].encodeType(frame, limits);
  }
251962
func NewDataFileWriter(output io.Writer, schema Schema, datumWriter DatumWriter) (writer *DataFileWriter, err error) {
	encoder := NewBinaryEncoder(output)
	datumWriter.SetSchema(schema)
	sync := []byte("1234567890abcdef") // TODO come up with other sync value

	header := &objFileHeader{
		Magic: magic,
		Meta: map[string][]byte{
			schemaKey: []byte(schema.String()),
			codecKey:  []byte("null"),
		},
		Sync: sync,
	}
	headerWriter := NewSpecificDatumWriter()
	headerWriter.SetSchema(objHeaderSchema)
	if err = headerWriter.Write(header, encoder); err != nil {
		return
	}
	blockBuf := &bytes.Buffer{}
	writer = &DataFileWriter{
		output:      output,
		outputEnc:   encoder,
		datumWriter: datumWriter,
		sync:        sync,
		blockBuf:    blockBuf,
		blockEnc:    NewBinaryEncoder(blockBuf),
	}

	return
}
1085169
private void encodeUnion(GeneratorAdapter mg, TypeToken<?> outputType, Schema schema,
                           int value, int encoder, int schemaLocal, int seenRefs) {
    Label nullLabel = mg.newLabel();
    Label endLabel = mg.newLabel();
    mg.loadArg(value);

    mg.ifNull(nullLabel);
    // Not null, write out 0 and then encode the value
    encodeInt(mg, 0, encoder);

    mg.loadThis();
    mg.loadArg(value);
    doCast(mg, outputType, schema.getUnionSchema(0));
    mg.loadArg(encoder);
    mg.loadArg(schemaLocal);
    mg.push(0);
    mg.invokeVirtual(Type.getType(Schema.class), getMethod(Schema.class, "getUnionSchema", int.class));
    mg.loadArg(seenRefs);
    mg.invokeVirtual(classType, getEncodeMethod(outputType, schema.getUnionSchema(0)));

    mg.goTo(endLabel);

    mg.mark(nullLabel);
    // Null, write out 1
    encodeInt(mg, 1, encoder);
    mg.mark(endLabel);
  }
61651
@Override
  public void encode(OutputStream out, TransactionSnapshot snapshot) {
    BinaryEncoder encoder = new BinaryEncoder(out);
    try {
      encoder.writeLong(snapshot.getTimestamp());
      encoder.writeLong(snapshot.getReadPointer());
      encoder.writeLong(snapshot.getWritePointer());
      // supporting old versions of codecs
      encodeObsoleteAttributes(encoder);
      encodeInvalid(encoder, snapshot.getInvalid());
      encodeInProgress(encoder, snapshot.getInProgress());
      encodeChangeSets(encoder, snapshot.getCommittingChangeSets());
      encodeChangeSets(encoder, snapshot.getCommittedChangeSets());

    } catch (IOException e) {
      LOG.error("Unable to serialize transaction state: ", e);
      throw Throwables.propagate(e);
    }
  }
798029
def write_int(fo, datum, schema=None):
    
    datum = (datum << 1) ^ (datum >> 63)
    while (datum & ~0x7F) != 0:
        fo.write(pack('B', (datum & 0x7f) | 0x80))
        datum >>= 7
    fo.write(pack('B', datum))
97011
public static void writeSchema(String outputPath, Schema schema, JavaSparkContext sc) throws IOException {
        writeStringToFile(outputPath, schema.toString(), sc);
    }
61863
private static function resolveEnum(
        DriverInterface $driver,
        array $schema,
        SQLServerColumn $column
    ) {
        $query = 'SELECT object_definition([o].[object_id]) AS [definition], '
            . "OBJECT_NAME([o].[object_id]) AS [name]\nFROM [sys].[objects] AS [o]\n"
            . "JOIN [sys].[sysconstraints] AS [c] ON [o].[object_id] = [c].[constid]\n"
            . "WHERE [type_desc] = 'CHECK_CONSTRAINT' AND [parent_object_id] = ? AND [c].[colid] = ?";

        $constraints = $driver->query($query, [$schema['object_id'], $schema['column_id']]);

        foreach ($constraints as $constraint) {
            $column->enumConstraint = $constraint['name'];
            $column->constrainedEnum = true;

            $name = preg_quote($driver->identifier($column->getName()));

            //We made some assumptions here...
            if (preg_match_all(
                '/' . $name . '=[\']?([^\']+)[\']?/i',
                $constraint['definition'],
                $matches
            )) {
                //Fetching enum values
                $column->enumValues = $matches[1];
                sort($column->enumValues);
            }
        }
    }
64917
function encodeType($value, \Plasma\ColumnDefinitionInterface $column): \Plasma\Types\TypeExtensionResultInterface {
        $type = \gettype($value);
        if($type === 'double') {
            $type = 'float';
        }
        
        if($type === 'object') {
            $classes = \array_merge(
                array(\get_class($value)),
                \class_parents($value),
                \class_implements($value)
            );
            
            /** @var \Plasma\Types\TypeExtensionInterface  $encoder */
            foreach($this->classTypes as $key => $encoder) {
                if(\in_array($key, $classes, true)) {
                    return $encoder->encode($value, $column);
                }
            }
        }
        
        /** @var \Plasma\Types\TypeExtensionInterface  $encoder */
        foreach($this->regularTypes as $key => $encoder) {
            if($type === $key) {
                return $encoder->encode($value, $column);
            }
        }
        
        if($this->enabledFuzzySearch) {
            /** @var \Plasma\Types\TypeExtensionInterface  $encoder */
            foreach($this->classTypes as $key => $encoder) {
                if($encoder->canHandleType($value, $column)) {
                    return $encoder->encode($value, $column);
                }
            }
            
            /** @var \Plasma\Types\TypeExtensionInterface  $encoder */
            foreach($this->regularTypes as $key => $encoder) {
                if($encoder->canHandleType($value, $column)) {
                    return $encoder->encode($value, $column);
                }
            }
        }
        
        throw new \Plasma\Exception('Unable to encode given value');
    }
172420
function encodeObject( encoder, object ) {

	// Check ByRef internally
	var id = encoder.lookupIRef( object );
	if (id > -1) { encodeIREF( encoder, id ); return; }

	// Check ByRef externally
	id = encoder.lookupXRef( object );
	if (id > -1) { encodeXREF( encoder, id); return }

	// Lookup object type
	var enc = encoder.profile.encode(object);
	if (!enc) {
		throw new Errors.XRefError('An object trying to encode was not declared in the object table!');
	}

	// Populate property table
	var eid = enc[0], propertyTable = enc[1]( object );

	// Check ByVal ref
	id = encoder.lookupIVal( propertyTable, eid );
	if (id > -1) 
		{ encodeIREF( encoder, id ); return; }

	// Keep this object for internal cross-refferencing
	encoder.log(LOG.OBJ,"eid="+eid+", properties="+propertyTable.length);
	encoder.keepIRef( object, propertyTable, eid );

	// Check if we should use 12-bit or 5-bit index
	if (eid < 32) {

		// Write entity opcode
		encoder.stream8.write( pack1b( PRIM_OP.OBJECT | OBJ_OP.KNOWN_5 | eid ) );
		encoder.counters.op_prm+=1;

	} else {

		// Split 12-bit number
		var eid_hi = (eid & 0xF00) >> 8,
			eid_lo = eid & 0xFF;

		// Write entity
		encoder.stream8.write( pack1b( PRIM_OP.OBJECT | OBJ_OP.KNOWN_12 | eid_hi ) );
		encoder.stream8.write( pack1b( eid_lo ) );
		encoder.counters.op_prm+=2;

	}

	// Write property table as an array
	encodeArray( encoder, propertyTable );

}