Skip to content

Invalid memory unit conversions #204

@1993alexey

Description

@1993alexey

I was writing unit tests for my functions that rely on this awesome library and found a serious problem with memory unit conversions.

Here is a complete code example

const { bytes, Measure, tebi } = require('safe-units')
console.log(Measure.of(1, tebi(bytes)).in(bytes))

The result was 256 B which is wrong. It should have been 1099511627776 B

After investigating this problem, I can see that the left shift operation doesn't produce the desired results due to overflow. It results in a 32 bit integer.

export const kibi: PrefixFn = Measure.prefix("Ki", 1 << 10); // 1024
export const mebi = Measure.prefix("Mi", 1 << 20); // 1048576
export const gibi = Measure.prefix("Gi", 1 << 30); // 1073741824
export const tebi = Measure.prefix("Ti", 1 << 40); // 256
export const pibi = Measure.prefix("Pi", 1 << 50); // 262144
export const exbi = Measure.prefix("Ei", 1 << 60); // 268435456
export const zebi = Measure.prefix("Zi", 1 << 70); // 64
export const yobi = Measure.prefix("Yi", 1 << 80); // 65536

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions