@@ -33,16 +33,17 @@ size_t *blocks_coords_from_pointer(void *p1, ndarray_obj_t *ndarray) {
3333 // This is a utility function, and is not exposed to the python interpreter
3434 blocks_block_obj_t * block = ndarray -> block ;
3535 size_t diff = (uint8_t * )p1 - (uint8_t * )block -> origin ;
36- printf ("pointer: 0x%p, 0x%p, 0x%p, %ld\n" , p1 , ndarray -> array , block -> origin , diff );
37- size_t accumulator = ndarray -> itemsize ;
36+ size_t stride = ndarray -> itemsize ;
3837 size_t * coords = m_new (size_t , ULAB_MAX_DIMS );
3938
40- for (uint8_t i = 0 ; i < ndarray -> ndim ; i ++ ) {
41- accumulator *= block -> shape [ULAB_MAX_DIMS - i - 1 ];
42- coords [ULAB_MAX_DIMS - i ] = diff % accumulator ;
43- // diff -= coords[ULAB_MAX_DIMS - i] * block->shape[ULAB_MAX_DIMS - i];
44- diff -= coords [ULAB_MAX_DIMS - i - 1 ] * block -> shape [ULAB_MAX_DIMS - i - 1 ];
45- printf ("accumulator: %ld\n" , diff );
39+ // first, calculate the very first stride
40+ for (uint8_t i = 0 ; i < block -> ndim - 1 ; i ++ ) {
41+ stride *= block -> shape [ULAB_MAX_DIMS - i - 1 ];
42+ }
43+ for (uint8_t i = block -> ndim ; i > 1 ; i -- ) {
44+ coords [ULAB_MAX_DIMS - i ] = diff / stride ;
45+ diff -= coords [ULAB_MAX_DIMS - i ] * block -> shape [ULAB_MAX_DIMS - i ];
46+ stride /= block -> shape [ULAB_MAX_DIMS - i + 1 ];
4647 }
4748 return coords ;
4849}
@@ -113,6 +114,7 @@ mp_obj_t blocks_new_ndarray(size_t n_args, const mp_obj_t *pos_args, mp_map_t *k
113114 ndarray -> flags = BLOCK_IS_READ_ONLY ;
114115 blocks_block_obj_t * block = m_new_obj (blocks_block_obj_t );
115116 block -> base .type = & blocks_block_type ;
117+ block -> ndim = ndarray -> ndim ;
116118 // store a pointer to the ndarray
117119 block -> ndarray = ndarray ;
118120
0 commit comments